![](/img/trans.png)
[英]How to Pass HashCode of a Control as a CommandParameter in WPF XAML
[英]How to pass property value of a control to “CommandParameter” property of same control in WPF
我正在關注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"
/>
視圖模型:
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...
}
}
在將綁定更改為CommandParameter="{Binding Name ,RelativeSource={RelativeSource Self}}"
(如Mr.B建議)將解決您的問題時,我建議不要將UI元素名稱發送給ViewModel。 這將“破壞” MVVM模式。 對每個“打開文件操作”執行命令。 這還將避免長的if(browserButtonName= "thisOrThat")
子句,該子句難以維護。 這也具有更多優點。 僅舉一個例子:您可以將此命令綁定到KeyBindings
。 例如, CTRL + O將調用OpenFileCommand。
而且,如果您想追求卓越,甚至可以使用Service 用MVVM模式來抽象您的OpenFileDialog WPF OpenFileDialog?
您不能將ElementName用於元素iteself,而應使用RelativeSource = Self:
<Button x:Name="btnBrowseFirmware1"
Grid.Row="2"
Grid.Column="1"
Width="135"
Height="35"
Command="{Binding OpenFileDialogCommand}"
CommandParameter="{Binding Name ,RelativeSource={RelativeSource Self}}"
Content="Browse "
Foreground="White"
/>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.