2016-08-03 64 views
0

通過CheckBox.IsChecked通過CheckBox.IsChecked綁定的DataTrigger源值沒有改變。CheckBox綁定沒有更新源

我有簡單的視圖模型

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> 

enter image description here 當我檢查CheckBox2的CheckBox1成爲檢查,但不更新源。如何使其更新源?

enter image description here

+0

嘗試 「{結合檢查1,模式=雙向]」 –

回答

1

這很容易說爲什麼:你失去了約束力,如果你對手動設置TrueIsChecked
刪除DataTrigger,改變你的視圖模型是這樣的:

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

你的代碼似乎是錯誤的。您應該正確發出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>