C# 第一次运行CanExecute时,CommandParameter返回null
我有以下XAML:C# 第一次运行CanExecute时,CommandParameter返回null,c#,wpf,xaml,datacontext,C#,Wpf,Xaml,Datacontext,我有以下XAML: <Button Margin="222,256,102,19" Content="Add Customer" Command="{Binding AddCustomers}"> <Button.CommandParameter> <MultiBinding Converter="{StaticResource MyMul
<Button Margin="222,256,102,19" Content="Add Customer" Command="{Binding AddCustomers}">
<Button.CommandParameter>
<MultiBinding Converter="{StaticResource MyMultiConverter}">
<Binding ElementName="Name" Path="SelectedItem"></Binding>
<Binding ElementName="Address" Path="SelectedValue"></Binding>
</MultiBinding>
</Button.CommandParameter>
</Button>
CanExecute(CanAddCustomers)第一次运行后,Convertor方法运行,然后返回我在CommandParameter中传递的值。这不会发生在其他奇怪的按钮命令上。。这是怎么回事?为什么不去掉命令参数,直接将
SelectedItem
和SelectedValue
目标属性绑定到视图模型的一些源属性?这将是解决此问题的首选MVVM方法。一般来说,设置单个控件的DataContext表示设计不佳。应为整个视图(即窗口或页面)设置DataContext。CustomerViewModel可能由主视图模型的属性提供,然后您可以编写命令=“{Binding CustomerViewModel.AddCustomers}”
。因为这两个SelectedItem
和SelectedValue
都已绑定到listview。当您在ListView中单击某个项目时,它们都会显示该项目的值。编辑我的问题以获得更好的解释,即使DataContext不存在,此问题仍然会发生
private bool CanAddCustomers(object CustomerInfo)
{
var CustomerInfoToCheck= (object[])CustomerInfo; // exception here the first time it runs because CustomerInfo is null. The second time this method runs, it returns the values I passed in CommandParameter
....
}