这已被多次提出不同的变化,但我无法让它们起作用。
在我的视图中单击复选框(在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
}
答案 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}"/>