2016-09-07 59 views
0

我在我的WPF應用程序視圖中使用了行標題中複選框的Datagrid。WPF。通過MultiBinding更改CheckBox IsChecked不會觸發CheckBox命令

<DataGrid.RowHeaderTemplate> 
<DataTemplate> 
    <Grid > 
     <CheckBox BorderThickness="0" 
        Command="{Binding DataContext.AssignPartsToGroupCommand, RelativeSource={RelativeSource FindAncestor, 
                       AncestorType={x:Type UserControl}}}"           
            > 
      <CheckBox.CommandParameter> 
       <MultiBinding Converter="{StaticResource PartsGroupAssignConverter}"> 
        <Binding Path="IsChecked" RelativeSource="{RelativeSource Self}" Mode="OneWay"/> 
        <Binding RelativeSource="{RelativeSource Mode=FindAncestor, 
                  AncestorType={x:Type DataGridRow}}" 
          Path="DataContext" Mode="OneWay"/> 
       </MultiBinding> 
      </CheckBox.CommandParameter> 
      <CheckBox.IsChecked> 
       <MultiBinding Converter="{StaticResource PartsGroupAssignedConverter}" Mode="OneWay"> 
        <Binding ElementName="partsGroupGrid" Path="SelectedItem.id"></Binding> 
        <Binding RelativeSource="{RelativeSource Mode=FindAncestor, 
                  AncestorType={x:Type DataGridRow}}" 
          Path="DataContext" Mode="OneWay"/> 
        <Binding Path="IsSelected" Mode="OneWay" 
          RelativeSource="{RelativeSource FindAncestor, 
           AncestorType={x:Type DataGridRow}}" 
          /> 
       </MultiBinding> 
      </CheckBox.IsChecked> 
     </CheckBox> 
    </Grid> 
</DataTemplate> 

正如你可以看到我綁定的CheckBox屬性「IsSelected」多個值,其中之一是DataGrid行選擇:

<Binding Path="IsSelected" 
      Mode="OneWay" 
      RelativeSource="{RelativeSource FindAncestor, 
            AncestorType={x:Type DataGridRow}}" 
           /> 

我的問題是 - 與複選框命令當我通過選擇行來檢查CheckBox時沒有觸發。但是當我手動(使用鼠標)觸發它時觸發。我該如何解決這個問題?

+0

缺少您的命令和轉換碼(也許你可以將其添加)。您也可以嘗試在以下位置添加UpdateSourceTrigger =「PropertyChanged」: ...和 WPFGermany

回答

0

根據CheckBox源代碼,不支持所需的方法 - 只有在點擊該命令後纔會調用該命令。

但是,您可以創建一個小的CheckBox後代來實現您所需的行爲。該後代將跟蹤CheckBox.IsChecked屬性的更改並執行命令。

你可以這樣說:

public class MyCheckBox : CheckBox { 
    static MyCheckBox() { 
     IsCheckedProperty.OverrideMetadata(typeof(MyCheckBox), new FrameworkPropertyMetadata((o, e) => ((MyCheckBox)o).OnIsCheckedChanged())); 
    } 

    readonly Locker toggleLocker = new Locker(); 
    readonly Locker clickLocker = new Locker(); 

    void OnIsCheckedChanged() { 
     if (clickLocker.IsLocked) 
      return; 
     using (toggleLocker.Lock()) { 
      OnClick(); 
     } 
    } 

    protected override void OnToggle() { 
     if (toggleLocker.IsLocked) 
      return; 
     base.OnToggle(); 
    } 

    protected override void OnClick() { 
     using (clickLocker.Lock()) { 
      base.OnClick(); 
     } 
    } 
} 

加鎖類:

class Locker : IDisposable { 
    int count = 0; 
    public bool IsLocked { get { return count != 0; } } 
    public IDisposable Lock() { 
     count++; 
     return this; 
    } 
    public void Dispose() { count--; } 
}