wpfpropertiesmultitargeting

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


I have a project that needs to target .NET Framework 3.5 and 4.5, and I want to set property of a WPF control according to the build target. E.g . I have a textblock, and I want its background to be Azure if the build target is 3.5, Cyan if the build target is 4.5 How can I do that?

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


Solution

  • You could use the 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.

    Your xaml should look something like that:

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

    With a property defined in the VM/code behind:

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