首页 > 解决方案 > 将 WPF 中按钮的内容动态更改为选定的文件名

问题描述

当单击按钮后选择文件时,我试图在 c# WPF 中动态更改按钮的内容名称。我在这种方法中使用 MVVM。我试图插入一个点击事件,但它在这种方法中不起作用,因为点击事件总是在命令事件之前发生。我在 StackExchange 中研究过解决方案,但我看到的通常是触发事件并创建一个调用多个命令的命令。我可以在最适合更改按钮内容名称的方法上使用一些指针。

我在 MVVM 中有以下层次结构(修改仍应遵循此层次结构)

在我的 XAML 中,我创建了一个按钮,Content="Import File"我想在选择文件时动态更改它。我在这里使用命令方法和我的视图方法中的委托方法来调用我的方法。

<Button  x:Name="SelectFile" Margin="0 0 0 0" Content="Import File"  Command="{Binding ImportExcelBtn, Mode=TwoWay}"/>

在视图模型中,我使用的是委托命令方法。我已经获得了文件名,string FileName但我似乎找不到绑定方法和更改按钮内容名称的方法。

public DelegateCommand ImportExcelBtn
    {
        get { return _importExcelBtn; }
        set
        {
            _importExcelBtn = value;
            SetPropertyChanged("ImportExcelBtn");
        }
    }

public ViewModel()
    {
        modelView = new ModelView();
        ImportExcelBtn = new DelegateCommand(ImportExcelFileAction);//From model
    }
private void ImportExcelFileAction()
        {
            excelFile = ImportFile();//get excel file from method
            string name = excelFile .ToString();
            int position = name.LastIndexOf("\\") + 1;
            string FileName = name.Substring(position, name.Length - position);
        }

在我的模型中,我有一种选择文件的方法。(我的脚本在这里运行成功)

太感谢了!

标签: c#wpfbuttonmvvm

解决方案


您可以将 绑定Content到 ViewModel 中的属性并在获取文件名时更改它。例如,在您的 ViewModel

public string ContentValue {get;set;} = "Import File";

在 Xaml

Content="{Binding ContentValue}" 

稍后,当您有文件名时,您可以更新ContentValue

private void ImportExcelFileAction()
{
excelFile = ImportFile();//get excel file from method
string name = excelFile .ToString();
int position = name.LastIndexOf("\\") + 1;
string FileName = name.Substring(position, name.Length - position);
ContentValue  = FileName;
OnPropertyChanged(nameof(ContentValue)); //Call Notify Property Changed
}

推荐阅读