0

如何将多个控件值绑定到我的视图模型中的单个属性

无效代码:

        <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>
4

1 回答 1

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 用于将一个元素值绑定到许多 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);
    }
于 2013-03-13T17:46:10.757 回答