为什么当尝试通过 Command 从 View 传递 Property 时 ViewModel 会返回 null?

问题描述 投票:0回答:0

所以我尝试将 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>

我的问题是:

  1. 为什么不起作用?
  2. 哪种绑定顺序?当我首先运行调试时,将是 Event_Click,然后是 CanExecute,然后是 Execute - 这里 MyProperty 已经从 Event_Click 设置,但无论如何 Command 都为空。
c# wpf mvvm binding relaycommand
© www.soinside.com 2019 - 2024. All rights reserved.