复选框绑定不更新源

CheckBox binding not updating source

通过 DataTrigger 源值更改 CheckBox.IsChecked 后,CheckBox.IsChecked 绑定的源值未更改。

我有简单的 ViewModel

public class ViewModel : INotifyPropertyChanged
    {    
        private bool check1;    
        public bool Check1
        {
            get { return check1; }
            set { check1 = value; NotifyPropertyChanged(); }
        }    

        private bool check2;    
        public bool Check2
        {
            get { return check2; }
            set { check2 = value; NotifyPropertyChanged(); }
        }

        #region Notify
        ...    
        #endregion
    }

简单XAML

<StackPanel Grid.Row="1">
        <CheckBox Content="Check1">
            <CheckBox.Style >
                <Style TargetType="{x:Type CheckBox}">
                    <Setter Property="IsChecked" Value="{Binding Check1, Mode=TwoWay}"/>
                    <Style.Triggers>
                        <DataTrigger Binding="{Binding Check2}" Value="True">
                            <Setter Property="IsChecked" Value="True"/>
                        </DataTrigger>
                    </Style.Triggers>
                </Style>
            </CheckBox.Style>
        </CheckBox>

        <CheckBox Content="Check2" IsChecked="{Binding Check2}"/>

        <TextBlock Text="{Binding Check1}" Name="uiCheckValue1"/>
        <TextBlock Text="{Binding Check2}" Name="uiCheckValue2"/>
    </StackPanel>

当我选中 CheckBox2 时,CheckBox1 变为选中状态,但源未更新。如何让它更新源?

原因很简单:如果您在 True 上手动设置 IsChecked,您将失去绑定。
删除 DataTrigger 并像这样更改您的 ViewModel:

public bool Check2{
    get { return check2; }
    set { 
          check2 = value; 
          if (value == true) Check1 = true;
          NotifyPropertyChanged(); 
        }
 }

您的代码似乎有误。您应该正确发出 PropertyChanged 事件以更新视图。 检查以下代码:

public class ViewModel : INotifyPropertyChanged
{    
    private bool check1;    
    public bool Check1
    {
        get { return check1; }
        set 
        { 
            check1 = value; 
            PropertyChanged(value, new PropertyChangedEventArgs("Check1")); 
        }
    }    

    private bool check2;    
    public bool Check2
    {
        get { return check2; }
        set 
        { 
            check2 = value;
            PropertyChanged(value, new PropertyChangedEventArgs("Check1")); 
        }
    }

    #region Notify
    ...    
    #endregion
}

同时将绑定更改为 TwoWay

<<CheckBox Content="Check2" IsChecked="{Binding Check2, Mode=TwoWay}"/>

<DataTrigger Binding="{Binding Check2, Mode=TwoWay}" Value="True">
<Setter Property="IsChecked" Value="True" />
</DataTrigger>

有点晚了,但如果你改变

<CheckBox Content="Check2" IsChecked="{Binding Check2}"/>

<CheckBox Content="Check2" IsChecked="{Binding Check2, UpdateSourceTrigger=PropertyChanged}"/>

你可以去掉后面所有的代码。复选框的默认设置类似于 LostFocus,这很烦人。