【发布时间】:2020-12-24 01:08:20
【问题描述】:
我有一个包含多列的 DataGrid。一列应该用作参考,但现在它的行为就像一个虚拟文本。如何使用 MVVM 模式(无事件)通过单击此文本来执行任何命令?
<DataGridTextColumn
Binding="{Binding RecipeName}"
Header="Recipe"
Width="1.5*"/>
【问题讨论】:
我有一个包含多列的 DataGrid。一列应该用作参考,但现在它的行为就像一个虚拟文本。如何使用 MVVM 模式(无事件)通过单击此文本来执行任何命令?
<DataGridTextColumn
Binding="{Binding RecipeName}"
Header="Recipe"
Width="1.5*"/>
【问题讨论】:
一种方法是通过重新定义列的 CellTemplate 在单元格中使用按钮。
这是一个例子:
<DataGrid ItemsSource="{Binding Items}">
<DataGrid.Columns>
<!-- Your first column -->
<DataGridTemplateColumn Header="Recipe">
<DataGridTemplateColumn.CellTemplate>
<!-- Let's redefine the cell template for our column -->
<ItemContainerTemplate>
<Button Content="{Binding RecipeName}" Command="{Binding MyCommand}">
<!-- Here we remove the button's default templating by overriding it -->
<Button.Template>
<ControlTemplate TargetType="Button">
<ContentPresenter Content="{TemplateBinding Content}" />
</ControlTemplate>
</Button.Template>
</Button>
</ItemContainerTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
</DataGrid.Columns>
</DataGrid>
【讨论】: