DataGridTemplateColumn.CellTemplate中的wpf bind checkbox命令

时间:2013-06-13 15:05:43

标签: wpf mvvm datagridtemplatecolumn datagridviewcheckboxcell

这已被多次提出不同的变化,但我无法让它们起作用。

在我的视图中单击复选框(在datagridTemplateColumn.cellTemplate中)时,我正在尝试在我的viewmodel中调用一个方法

<DataGrid ItemsSource="{Binding TransactionTypes}" AutoGenerateColumns="False" CanUserAddRows="False" x:Name="TransTypesGrid">
<DataGrid.Columns>
    <DataGridTemplateColumn>
        <DataGridTemplateColumn.CellTemplate>
            <DataTemplate>
                <CheckBox IsChecked="{Binding IsSelected, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"
                            Command="{Binding DataContext.UpdateCommand, ElementName=TransTypesGrid}" />
            </DataTemplate>
        </DataGridTemplateColumn.CellTemplate>
    </DataGridTemplateColumn>
    <DataGridTextColumn Header="Transaction Type" Binding="{Binding TransTypeDesc}" />
</DataGrid.Columns>

和我的viewModel

public DelegateCommand UpdateCommand { get; set; }

public myConstructor()
{    
  this.UpdateCommand = new DelegateCommand(Update);
}

private void Update()
{
    //this stuff works, it's just not getting called when a checkbox get's (un)checked
    //stuff that goes though the DataGrid's item source's IsSelected property
}

2 个答案:

答案 0 :(得分:4)

您应该在命令绑定中使用Self绑定

<DataTemplate>
   <CheckBox IsChecked="{Binding IsSelected, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"
      Command="{Binding DataContext.UpdateCommand,RelativeSource={RelativeSource Mode=Self}}" />
</DataTemplate>

答案 1 :(得分:2)

如果在ViewModel中的模型和命令中选择IsSelected,则此代码有效。

<CheckBox IsChecked="{Binding IsSelected, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"
Command="{Binding 
RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type Window}}, 
Path=DataContext.UpdateCommand}"/>