我使用具有相同数据类型的多个列的 DataGrid。我想对列使用 DataGridTemplateColumn,并为 CellTemplate 定义一个 DataTemplate,为 CellEditingTemplate 定义一个 DataTemplate。
是否可以将 DataTemplates 的文本绑定到相应的源属性?
视图模型:
class Item : Notifier
{
private String name;
public String Name
{
get { return this.name; }
set
{
this.name = value;
OnPropertyChanged("Name");
}
}
private String comment = String.Empty;
public String Comment
{
get { return this.comment; }
set
{
this.comment = value;
OnPropertyChanged("Comment");
}
}
}
class MainWindowsViewModel : Notifier
{
private List<Item> data = new List<Item>();
public List<Item> Data { get { return this.data; } }
查看:
<Window.Resources>
<viewmodel:MainWindowsViewModel x:Key="vm"/>
<!-- readonly template -->
<DataTemplate x:Key="dt">
<TextBlock Background="AliceBlue" Margin="5"
Text="{Binding ???}"/>
</DataTemplate>
<!-- editing template -->
<DataTemplate x:Key="edt">
<TextBox Background="LightCoral" Margin="10"
Text="{Binding ???}"/>
</DataTemplate>
</Window.Resources>
<Grid>
<DataGrid
DataContext="{StaticResource vm}"
ItemsSource="{Binding Data}"
HorizontalAlignment="Left"
Margin="10,10,10,10"
VerticalAlignment="Top"
>
<DataGrid.Columns>
<DataGridTemplateColumn
Header="Name"
CellTemplate="{StaticResource dt}"
CellEditingTemplate="{StaticResource edt}"
/>
<DataGridTemplateColumn
Header="Comment"
CellTemplate="{StaticResource dt}"
CellEditingTemplate="{StaticResource edt}"
/>
</DataGrid.Columns>
</DataGrid>
</Grid>
DataContext
的 DataTemplate
是always 模板化数据类型的实例。
设置
DataTemplate.DataType
属性确实很有帮助,因为这将使设计者能够提供代码建议。
在您的情况下,模板的
DataContext
是一个 Item
实例:
<Window.Resources>
<!-- readonly template -->
<DataTemplate x:Key="dt"
DataType="Item">
<StackPanel>
<TextBlock Text="{Binding Name}" />
<TextBlock Text="{Binding Comment}" />
</DataTemplate>
</Window.Resources>
并尽可能避免字符串文字:
OnPropertyChanged("Comment");
应该成为
OnPropertyChanged(nameof(this.Comment));