侧边栏壁纸
博主头像
陌上花 博主等级

回首万事皆休

  • 累计撰写 72 篇文章
  • 累计创建 11 个标签
  • 累计收到 0 条评论

目 录CONTENT

文章目录
WPF

WPF使用DataTemplate

种向日葵的人
2025-05-31 / 0 评论 / 0 点赞 / 15 阅读 / 0 字

Why

  • 最近在看公司的代码,使用的是WPF的一个测试软件,发现了一种蛮好玩的写法,就是使用DataTemplate来控制显示的内容,以下是我写的一个简单的示例。

How

  • ViewModel
public partial class DeviceViewModel : ObservableObject
{

    [RelayCommand]
    private void ShowNullMsg()
    {
        MessageBox.Show("Device Name is null");
        DeviceStr = "Device1";
    }

    [ObservableProperty]
    private string? deviceName = "Device Name";
    [RelayCommand]
    private void ShowDeviceTemplate()
    {
        MessageBox.Show($"Device Name: {DeviceName}");
        DeviceStr = null;
    }

    [ObservableProperty]
    private string? deviceStr;
}
  • XAML
<UserControl
    x:Class="MyWPF.DeviceControl"
    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:local="clr-namespace:MyWPF"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    d:DataContext="{d:DesignInstance local:DeviceViewModel,
                                     IsDesignTimeCreatable=True}"
    d:DesignHeight="450"
    d:DesignWidth="800"
    mc:Ignorable="d">
    <UserControl.DataContext>
        <local:DeviceViewModel />
    </UserControl.DataContext>
    <UserControl.Resources>
        <DataTemplate x:Key="NullTemplate">
            <Button Command="{Binding ShowNullMsgCommand}" Content="Show Null Template" />
        </DataTemplate>
        <DataTemplate x:Key="DeviceTemplate">
            <StackPanel Orientation="Vertical">
                <TextBlock Text="{Binding DeviceName, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" />
                <Button Command="{Binding ShowDeviceTemplateCommand}" Content="Show Device Template" />
            </StackPanel>
        </DataTemplate>
    </UserControl.Resources>
    <Border Background="White">
        <ContentPresenter
            HorizontalAlignment="Center"
            VerticalAlignment="Center"
            Content="{Binding}">
            <ContentPresenter.Style>
                <Style TargetType="{x:Type ContentPresenter}">
                    <Style.Triggers>
                        <DataTrigger Binding="{Binding DeviceStr}" Value="{x:Null}">
                            <Setter Property="ContentTemplate" Value="{StaticResource NullTemplate}" />
                        </DataTrigger>
                        <DataTrigger Binding="{Binding DeviceStr}" Value="Device1">
                            <Setter Property="ContentTemplate" Value="{StaticResource DeviceTemplate}" />
                        </DataTrigger>
                    </Style.Triggers>
                </Style>
            </ContentPresenter.Style>
        </ContentPresenter>
    </Border>
</UserControl>

Tips

  • 其实使用DataTemplate真的是一个很好的技巧,我之前用的不是很多,现在发现使用还是很方便的。
0
博主关闭了所有页面的评论