【问题标题】:Changing content of a button in WPF dynamically to selected file name将 WPF 中按钮的内容动态更改为选定的文件名
【发布时间】:2020-04-30 18:44:06
【问题描述】:

当单击按钮后选择文件时,我试图在 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# wpf button mvvm


    【解决方案1】:

    您可以将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
    }
    

    【讨论】:

    • 你是我的救星。感谢您扩展我关于将值从视图模型绑定到 XAML 的知识。我要补充一件事,在您的评论中,您已经声明使用“NotifyPropertyChange”(我已经编辑并等待同行评审),但这会导致我的脚本出错。我不得不改用“OnPropertyChange”。上帝保佑!
    猜你喜欢
    • 1970-01-01
    • 2012-04-16
    • 1970-01-01
    • 1970-01-01
    • 2019-02-22
    • 1970-01-01
    • 2012-05-16
    • 1970-01-01
    • 2011-03-17
    相关资源
    最近更新 更多