我正在尝试将表头绑定到我的ViewModel中的属性。
<Window x:Class="MyProject.Views.Dialogs.ItemsDialog"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:MyProject"
mc:Ignorable="d"
Height="300" Width="600" MinWidth="200" MinHeight="200">
<Window.Resources>
<local:ViewModelLocator x:Key="Locator" />
</Window.Resources>
<Window.DataContext>
<Binding Source="{StaticResource Locator}" Path="ItemsDialogModel" />
</Window.DataContext>
<Window.Title>
<Binding Path="Strings.ItemsDialogTitle" />
</Window.Title>
<Grid Margin="10">
<Grid.RowDefinitions>
<RowDefinition Height="*"></RowDefinition>
<RowDefinition Height="Auto"></RowDefinition>
<RowDefinition Height="Auto"></RowDefinition>
</Grid.RowDefinitions>
<DataGrid ItemsSource="{Binding Items}">
<DataGrid.Columns>
<DataGridTextColumn Binding="{Binding Name}" Header="{Binding Strings.ItemNameHeader}" />
<DataGridTextColumn Binding="{Binding Name}" Header="{Binding Path=DataContext.Strings.ItemNameHeader, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type Window}}}" />
// ...
</DataGrid>
<TextBlock Text="{Binding Strings.ItemsNameHeader}" Grid.Row="2" />
</Grid>
</Window>
窗口标题绑定和DataGrid
之外的其他绑定工作正常。网格中的数据也成功绑定。例如,TextBlock
下的DataGrid
可以正常运行。但是上面代码中的两种标头绑定方式都不起作用。
如何将DataGridTextColumn
的标头绑定到视图模型的Strings.ItemNameHeader
属性?我应该使用RelativeSource吗?