c# - 如何在运行时更改数据模板?

标签 c# wpf xaml datagrid datatemplate

在我的应用程序中,我有一个 CheckBox,我希望当它被选中时,显示一个 DataTemplate,当它未被选中时,显示另一个。

这是带有两个模板的片段

    <DataGrid x:Name="dataGrid" LoadingRow="dataGrid_LoadingRow_1" ItemsSource="{Binding Item3}"
        <DataGrid.RowHeaderTemplate>
            <DataTemplate>
                <TextBlock Text="{Binding StudentId}"/>
            </DataTemplate>                
            <DataTemplate>
                <TextBlock Text="{Binding FullName}"/>
            </DataTemplate>
        </DataGrid.RowHeaderTemplate>
    </DataGrid>

我不确定如何实现它,但我想我需要我的用户控件中的接口(interface) INotifyPropertyChanged 来触发或仅确定更改的时间。

最佳答案

您只能通过触发器来完成。如果以上是您的要求。您可以简单地通过触发器来完成。我试过了,它对我有用。

   <Window.Resources>
    <ControlTemplate x:Key="MyRowHeaderTemplate">
        <TextBlock x:Name="RowHeaderTxt" 
                   Text="{Binding StudentId, RelativeSource={RelativeSource AncestorType={x:Type Window}}}"/>
        <ControlTemplate.Triggers>
            <DataTrigger Binding="{Binding Path=IsChecked, ElementName=MyCheckBox}" 
                         Value="True">
                <Setter TargetName="RowHeaderTxt" Property="Text" 
                        Value="{Binding FullName, RelativeSource={RelativeSource AncestorType={x:Type Window}}}"/>
            </DataTrigger>
        </ControlTemplate.Triggers>
    </ControlTemplate>
</Window.Resources>
<StackPanel>
    <CheckBox x:Name="MyCheckBox"/>
    <DataGrid ItemsSource="{Binding Item3}" AutoGenerateColumns="True">
        <DataGrid.RowHeaderTemplate>
            <DataTemplate>
                <ContentControl Template="{StaticResource MyRowHeaderTemplate}"/>
            </DataTemplate>
        </DataGrid.RowHeaderTemplate>
    </DataGrid>
</StackPanel>

试试这个。

关于c# - 如何在运行时更改数据模板?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14430196/

相关文章:

c# - 在 Cake Build 中隐藏服务密码

c# - gRPC 与 Asp.net Core Mvc 一起运行

c# - 如何以编程方式更改列表框中所选项目的背景颜色?

wpf - 测试驱动开发 - WPF

c# - ASP 中的弹出式警报

c# - azure "The remote server returned an error: (530) Not logged in."

.net - XAML 正在使用先前的绑定(bind)调用 get

c# - WPF 选择器——如何确保它只允许单选而不允许多选?

wpf - VirtualizingStackPanel 的缺点是什么?

xaml - Xamarin.Forms:xaml。给按钮添加 "click"动画