我如何拥有 DataGrid 模板并根据需要更改它们

How do I have DataGrid Templates and change them as needed

我正忙于一项基本功能,在该功能中,用户会看到一个 ListBox,其中包含数据库中的 table。 ListBox 右侧是一个 DataGrid,它显示 table 中的字段。这意味着每次 table 被 selected 时,列都会改变,这就是我的问题所在。我知道自动列生成功能,但由于我想提供自己的列名,因此我需要手动执行。我已经阅读了当自动列生成处于活动状态时您可以处理更改名称的事件,但由于我使用的是 MVVM,所以我想避免使用代码隐藏文件进行事件处理。 我的想法是创建几个模板,然后在 DataGrid 内使用触发器以 select 正确的列布局。这就是我现在所拥有的。 模板:

<UserControl.Resources>
    <DataTemplate x:Key="template_measurement">
        <DataGrid>
            <DataGrid.Columns>
                <DataGridTextColumn Header="ID" Binding="{Binding id}"/>
                <DataGridTextColumn Header="Name" Binding="{Binding name}"/>
                <DataGridTextColumn Header="Latitude" Binding="{Binding source_latitude}"/>
                <DataGridTextColumn Header="Longitude" Binding="{Binding source_longitude}"/>
            </DataGrid.Columns>
        </DataGrid>
    </DataTemplate>

    <DataTemplate x:Key="template_realestate">
        <DataGrid>
            <DataGrid.Columns>
                <DataGridTextColumn Header="ID" Binding="{Binding id}"/>
                <DataGridTextColumn Header="Name" Binding="{Binding name}"/>
            </DataGrid.Columns>
        </DataGrid>
    </DataTemplate>
</UserControl.Resources>  

DataGrid:

<DataGrid AutoGenerateColumns="False" 
          Name="grdData" 
          HorizontalAlignment="Left" 
          Margin="10,10,0,0" 
          Grid.Row="2" 
          VerticalAlignment="Top" 
          Height="200" 
          Width="500"
          ItemsSource="{Binding Path=SelectedTable}">

        <DataGrid.Triggers>
            <Trigger Property="{Binding Path=SelectedTableName}" Value="measurement">
                <Setter Property="DataGrid" Value="{StaticResource template_measurement}"/>
            </Trigger>
        </DataGrid.Triggers>

</DataGrid>

以上内容无效,我怀疑它可能有严重错误,但希望能说明我正在尝试实现的目标。 SelectedTableName 属性 是一个字符串,其中包含当前 selected table.

的名称

如何让 DataGrid 使用我根据 SelectedTableName 值提供的模板之一?

嗯,我认为你的方法有一半是正确的,一半不正确,

您可以使用 ContentControl 然后设置其内容模板,而不是拥有数据模板然后将其设置为网格,就像您现在正在尝试的那样。