如何将多个控件值绑定到viewmodel
中的单个属性无效代码:
<MultiBinding Converter="{StaticResource myMultiConverter}">
<!--Convert From these element-->
<From ElementName="check1" Path="IsChecked" />
<From ElementName="check2" Path="IsChecked" />
<From ElementName="check3" Path="IsChecked" />
<From ElementName="check4" Path="IsChecked" />
<!--To Viewmodel Property-->
<To ElementName="myViewModelProperty" />
</MultiBinding>
<CheckBox Name="check1"></CheckBox>
<CheckBox Name="check2"></CheckBox>
<CheckBox Name="check3"></CheckBox>
<CheckBox Name="check4"></CheckBox>
答案 0 :(得分:0)
像往常一样在物业上绑定
<CheckBox Name="check1" IsChecked="{Binding Path=myViewModelProperty}" />
<CheckBox Name="check2" IsChecked="{Binding Path=myViewModelProperty}" />
<CheckBox Name="check3" IsChecked="{Binding Path=myViewModelProperty}" />
<CheckBox Name="check4" IsChecked="{Binding Path=myViewModelProperty}" />
然后,在ViewModel中:
public Boolean myViewModelProperty
{
get { ... }
set { ... }
}
同样在ViewModel中,需要时:
this.RaisePropertyChanged<Boolean>(() => this.myViewModelProperty);
如果需要,您可以在一个属性上绑定尽可能多的元素值(即使我不理解4具有相同属性的复选框^^)
MultiBinding用于将ONE元素值绑定到MANY ViewModel属性。
修改:考虑到必须将4复选框转换为枚举这一事实:
<CheckBox Name="check1" IsChecked="{Binding Path=myViewModelProperty1}" />
<CheckBox Name="check2" IsChecked="{Binding Path=myViewModelProperty2}" />
<CheckBox Name="check3" IsChecked="{Binding Path=myViewModelProperty3}" />
<CheckBox Name="check4" IsChecked="{Binding Path=myViewModelProperty4}" />
public Boolean myViewModelProperty1
{
get
{
return this.b1;
}
set
{
this.b1 =value;
this.EvaluateMyEnum();
}
}
public Boolean myViewModelProperty2
{
get
{
return this.b2;
}
set
{
this.b2 =value;
this.EvaluateMyEnum();
}
}
public Boolean myViewModelProperty3
{
get
{
return this.b2;
}
set
{
this.b2 =value;
this.EvaluateMyEnum();
}
}
public Boolean myViewModelProperty4
{
get
{
return this.b4;
}
set
{
this.b4 =value;
this.EvaluateMyEnum();
}
}
void EvaluateMyEnum()
{
this.MyViewModelEnum = ......;
this.RaisePropertyChanged<MyEnum>(() => this.myViewModelEnum);
}