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

How to set style of a WPF control according to target?

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

<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>

使用 Interaction.Behaviors 可以做到这一点,您可以在样式中包含的 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();

希望对您有所帮助。

您可以使用 Environment.Version that returns the CLR version. The idea here is to define a DataTrigger in your xaml bound to a boolean, true if the version starts with 4, false otherwise (.net 3.5 has a CLR version that starts with 2), take a look at the CLR versions here.

您的 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/code后面:

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