Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/wpf/12.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/visual-studio-2008/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
WPF:在代码隐藏中创建到嵌套属性的绑定_Wpf_Xaml_Binding_Viewmodel - Fatal编程技术网

WPF:在代码隐藏中创建到嵌套属性的绑定

WPF:在代码隐藏中创建到嵌套属性的绑定,wpf,xaml,binding,viewmodel,Wpf,Xaml,Binding,Viewmodel,我的xaml文件中有以下多重绑定: <MyControl:CommandParameter> <MultiBinding Converter="{commonConverters:MultiBindingConverter}"> <Binding Path="CurrentItem.Id" /> <Binding Path="SelectedItem.Count

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

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

如何在viewmodel中定义此多重绑定? 或者,如果不可能,我如何在viewmodel中定义每次Id或计数更改时都会触发命令的CanExecute

另一个困难是CurrentItem和SelectedItem在初始化后可能为null,并且在使用应用程序时将被初始化


谢谢

要告诉WPF您的命令可能已变为可执行或不可执行,可以使用事件。它将使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();
        }
    }
}

CanExecute
是一个单独的绑定,而不是上述多重绑定的一部分。它绑定到的ICommand应该只计算这两个属性。您不应该在VM中定义绑定,这是糟糕的设计(VM应该不知道它绑定到的视图)。