DataGridTemplateColumn.CellTemplate 中的 wpf 绑定复选框命令
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17090540/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
wpf bind checkbox command inside DataGridTemplateColumn.CellTemplate
提问by Charlie Wynn
This has been asked several times with different variations but I can't get any of them to work.
这已经被问过几次不同的变化,但我无法让他们中的任何一个工作。
I'm trying to get a method called in my viewmodel when a checkbox (in a datagridTemplateColumn.cellTemplate) is clicked in my view
当在我的视图中单击复选框(在 datagridTemplateColumn.cellTemplate 中)时,我试图在我的视图模型中调用一个方法
<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>
and in my viewModel
在我的 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
}
回答by Colin
You should use Selfbinding in your command binding
您应该Self在命令绑定中使用绑定
<DataTemplate>
<CheckBox IsChecked="{Binding IsSelected, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"
Command="{Binding DataContext.UpdateCommand,RelativeSource={RelativeSource Mode=Self}}" />
</DataTemplate>
回答by Jugal Panchal
This code works if IsSelected in model and command in ViewModel.
如果模型中的 IsSelected 和 ViewModel 中的命令,则此代码有效。
<CheckBox IsChecked="{Binding IsSelected, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"
Command="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType= {x:Type Window}},
Path=DataContext.UpdateCommand}"/>

