将多个元素值绑定到视图模型中的单个属性
本文关键字:模型 单个 属性 视图 元素 绑定 | 更新日期: 2023-09-27 18:03:40
如何将多个控件值绑定到视图模型中的单个属性
NOT VALID CODE:
<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>
按惯例绑定属性
<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用于将一个元素值绑定到多个ViewModel属性。
Edit:考虑到4复选框必须转换为enum:
<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);
}