Ahs*_*san 2 c# data-binding wpf mvvm
我遵循 MVVM 模式。我想将控件的属性值传递给同一控件的“CommandParameter”属性。但是正在面临“对象引用未设置到对象实例”的运行时异常。
WPF:
<Button
x:Name="btnBrowseFirmware1"
Grid.Row="2"
Grid.Column="1"
Width="135"
Height="35"
Command="{Binding OpenFileDialogCommand}"
CommandParameter="{Binding Name ,ElementName=btnBrowseFirmware1}"
Content="Browse "
Foreground="White"
/>
Run Code Online (Sandbox Code Playgroud)
视图模型:
public class ConfigurationParametersViewModel : WorkspaceViewModelBase
{
public ICommand OpenFileDialogCommand { get; private set; }
public ConfigurationParametersViewModel()
: base("ConfigurationParameters", true)
{
OpenFileDialogCommand = new RelayCommand<string>(OpenFileDialogCommandFunc);
}
private void OpenFileDialogCommandFunc(string browseButtonName)
{
OpenFileDialog fileDialog = new OpenFileDialog();
Some Code...
}
}
Run Code Online (Sandbox Code Playgroud)
虽然更改绑定CommandParameter="{Binding Name ,RelativeSource={RelativeSource Self}}"(如 B 先生建议的那样)可以解决您的问题,但我建议不要将 UI 元素名称发送到 ViewModel。这将“打破”MVVM 模式。为每个打开文件操作创建一个命令。if(browserButtonName= "thisOrThat")这也将避免出现难以维护的长子句。这也有更多的优点。仅举一例:您可以将此命令绑定到KeyBindings. 例如CTRL+O将调用 OpenFileCommand。
如果您想追求卓越,您甚至可以使用服务通过 MVVM 模式抽象您的 OpenFileDialog WPF OpenFileDialog?
| 归档时间: |
|
| 查看次数: |
6379 次 |
| 最近记录: |