如何根据目标设置WPF控件的样式



我有一个项目需要以.NET Framework 3.5和4.5为目标,我想根据构建目标设置WPF控件的属性。例如,我有一个文本块,如果构建目标是3.5,我希望它的背景是Azure,如果构建对象是4.5,我希望背景是Cyan。我该怎么做?

<Window x:Class="WpfAppMultipleTarget.MainWindow"
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:WpfAppMultipleTarget"
mc:Ignorable="d"
Title="MainWindow" Height="300" Width="300">
<Grid>
<Grid.Resources>
<Style TargetType="{x:Type TextBlock}">
<Setter Property="Background" Value="Azure"/> <!-- If target is net framework 3.5 -->
<Setter Property="Background" Value="Cyan"/> <!-- If target is net framework 4.5 -->
</Style>
</Grid.Resources>
<TextBlock>Hello</TextBlock>
</Grid>

您可以使用返回CLR版本的Environment.Version。这里的想法是在xaml中定义一个绑定到布尔值的DataTrigger,如果版本以4开头,则为true,否则为false(.net 3.5的CLR版本以2开头(,请查看此处的CLR版本。

你的xaml应该是这样的:

<....
Title="MainWindow" Height="450" Width="800" DataContext="{Binding RelativeSource={RelativeSource Self}}">
<Window.Resources>
</Window.Resources>
<Grid>
<Grid.Resources>
<Style TargetType="{x:Type TextBlock}">
<Style.Triggers>
<DataTrigger Binding="{Binding IsAbove4}" Value="True" >
<Setter Property="Background" Value="Cyan"/>
</DataTrigger>
</Style.Triggers>
<Setter Property="Background" Value="Azure"/>
</Style>
</Grid.Resources>
<TextBlock>Hello</TextBlock>
</Grid>

具有在VM/代码隐藏中定义的属性:

public bool IsAbove4 { get; set; } = Environment.Version.ToString().StartsWith("4");

通过交互可以做到这一点。行为可以在样式中包含的XAML中设置此属性。在行为内部,您可以阅读框架版本。下面是一个例子。

<Style TargetType="{x:Type TextBox}">
<Style.Setters>
<Setter Property="i:Interaction.Behaviors">
<Setter.Value>
<local:BehaviorName/>
<local:BehaviorName/>
</Setter.Value>
</Setter>
</Style.Setters>
</Style>

您可以使用此代码读取行为中的框架版本

string version = Assembly.GetExecutingAssembly().GetReferencedAssemblies().Where(c => c.Name.Contains("mscorlib")).FirstOrDefault().Version.ToString();

希望这能有所帮助。

最新更新