Why
- 最近在看公司的代码,使用的是
WPF
的一个测试软件,发现了一种蛮好玩的写法,就是使用DataTemplate
来控制显示的内容,以下是我写的一个简单的示例。
How
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;
}
<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
真的是一个很好的技巧,我之前用的不是很多,现在发现使用还是很方便的。