c# - 将 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);
}
在我的模型中,我有一种选择文件的方法。(我的脚本在这里运行成功)
太感谢了!
解决方案
您可以将 绑定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
}
推荐阅读
- python - Flask WTF 错误 - CSRF 会话令牌丢失(但实际上没有)
- python - sklearn管道转换ValueError,期望值不等于训练值
- swift - swift如何为此函数创建完成处理程序
- file - SSIS 和配置文件
- javascript - React JS 帮助:调用 react-papaparse 函数导致调用无限循环
- yarnpkg - 我看到'yarn install --network-timeout 1000000000'来增加超时。有谁知道这是多少秒?
- android - Android BottomSheet 和动态内容
- python - 多处理 [concurrent.futures.ProcessPoolExecutor] 未正确调用函数
- json - 将数据发布到 Json 时返回“未定义”错误
- r - R ggplotly() 和颜色注释 - 你是怎么做的?