2016-09-07 149 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--; } 
}