【问题标题】:WPF: create a binding to a nested property in code behindWPF:在后面的代码中创建到嵌套属性的绑定
【发布时间】:2021-03-24 19:36:26
【问题描述】:

我的 xaml 文件中有以下多重绑定:

<MyControl:CommandParameter>
    <MultiBinding Converter="{commonConverters:MultiBindingConverter}">
         <Binding Path="CurrentItem.Id" />
         <Binding Path="SelectedItem.Count" />
     </MultiBinding>
</Mycontrol:CommandParameter>

如何在我的视图模型中定义这种多重绑定? 或者,当这不可能时,如何在我的视图模型中定义每次 Id 或 Count 更改时都会触发命令的 CanExecute?

另一个难点是CurrentItem和SelectedItem在初始化后可以为null,在使用应用的时候会被初始化。

谢谢!

【问题讨论】:

  • CanExecute 是一个单独的绑定,不是上述多重绑定的一部分。它所绑定的 ICommand 应该简单地评估有问题的两个属性。而且你不应该在你的虚拟机中定义一个绑定,这是一个糟糕的设计(虚拟机应该不知道它所绑定的视图)。

标签: wpf xaml binding viewmodel


【解决方案1】:

要告诉 WPF 您的命令可能已变为可执行或不可执行,您可以使用ICommand.RaiseCanExecuteChanged 事件。它会让 WPF 调用你的命令的CanExecute 方法。

由于您没有提供 ViewModel 和 SelectedItem/CurrentItem 的代码,以下示例可能不代表您的用例,但它会为您提供总体思路。

考虑使用以下自定义命令类:

public class MyCommand : ICommand
{
    public EventHandler CanExecuteChanged;
    public void Execute(object parameter)
    {
        // do some stuff
    }
    public bool CanExecute(object parameter)
    {
        // determine if command can be executed
    }
    public void RaiseCanExecuteChanged()
    {
        this.CanExecuteChanged?.Invoke(this, EventArgs.Empty);
    }
}

在您的 ViewModel 中,您可以拥有如下所示的内容

public class MyViewModel
{
    private int _id;
    public MyCommand SomeCommand { get; set; }
    public int Id 
    { 
        get => _id;
        set
        {
            // do other stuff (ie: property changed notification)
            SomeCommand.RaiseCanExecuteChanged();
        }
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-04-10
    • 1970-01-01
    • 2015-11-07
    • 2013-11-27
    • 1970-01-01
    • 2011-02-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多