首页 > 解决方案 > 如何根据目标设置 WPF 控件的样式?

问题描述

我有一个需要针对 .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>

标签: wpfpropertiesmultitargeting

解决方案


可以使用 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();

希望这可以帮助。


推荐阅读