所以我尝试将 MyProperty 从 View 的代码隐藏通过 Command 传递到 ViewModel。它看起来像这样:
视图:代码隐藏.xaml.cs
public partial class MainWindow : Window
{
public string MyProperty { get; set; }
public MainWindow()
{
InitializeComponent();
}
private void Test_Click(object sender, RoutedEventArgs e)
{
MyProperty = "test click";
}
}
查看:.xaml
<MenuItem Header="Test" CommandParameter="{Binding ElementName=MainWindow, Path=MyProperty}" Command="{Binding Test}" Click="Test_Click"></MenuItem>
视图模型:
private RelayCommand _test;
public RelayCommand Test {
get
{
if (_test != null)
{
return _test;
}
return _test = new RelayCommand(obj =>
{
MessageBox.Show($"{obj}"); // here obj = null why?
});
}
}
继电器命令:
internal class RelayCommand : ICommand
{
private Action<object> _execute;
private Func<object, bool> _canExecute;
public event EventHandler CanExecuteChanged
{
add { CommandManager.RequerySuggested += value; }
remove { CommandManager.RequerySuggested -= value; }
}
public RelayCommand(Action<object> execute, Func<object, bool> canExecute = null)
{
_execute = execute;
_canExecute = canExecute;
}
public bool CanExecute(object parameter)
{
return _canExecute == null || _canExecute(parameter);
}
public void Execute(object parameter)
{
_execute(parameter);
}
}
还尝试使用RelativeSource代替ElementName,但不起作用:
<MenuItem Command="{Binding DataContext.Test, RelativeSource={RelativeSource AncestorType=views:MainWindow}}" CommandParameter="{Binding RelativeSource={RelativeSource AncestorType=views:MainWindow}, Path=MyProp}" Click="Test_Click"></MenuItem>
我的问题是: