WPF根据内容将标签背景设置为图像

时间:2016-04-28 06:48:53

标签: c# wpf xaml data-binding triggers

我有以下Xaml代码,我有标签触发器。我想要一个触发器,将图像放在背景中以获取某些内容值。我如何将其作为触发器?

 <Window.Resources>
    <DataTemplate x:Key="DataTemplate_Level2">
        <Label Content="{Binding }" Width="70" Height="70" HorizontalContentAlignment="Center" x:Name="Background">
        </Label>
        <DataTemplate.Triggers>
            <DataTrigger Binding="{Binding}" Value="1">
                <Setter TargetName="Background" Property="Background" Value="Black"/>
            </DataTrigger>
            <DataTrigger Binding="{Binding}" Value="5">
                <Setter TargetName="Background" Property="Background" Value="Image"/>
            </DataTrigger>
            <DataTrigger Binding="{Binding }" Value="9">
                <Setter TargetName="Background" Property="Background" Value="Green"/>
            </DataTrigger>
            <DataTrigger Binding="{Binding}" Value="7">
                <Setter TargetName="Background" Property="Background" Value="blue"/>
            </DataTrigger>
        </DataTemplate.Triggers>
    </DataTemplate>
    <DataTemplate x:Key="DataTemplate_Level1">
        <ItemsControl ItemsSource="{Binding}" ItemTemplate="{DynamicResource DataTemplate_Level2}">
            <ItemsControl.ItemsPanel>
                <ItemsPanelTemplate>
                    <StackPanel Orientation="Horizontal"/>
                </ItemsPanelTemplate>
            </ItemsControl.ItemsPanel>
        </ItemsControl>
    </DataTemplate>
</Window.Resources>

1 个答案:

答案 0 :(得分:3)

只需使用ImageBrush作为背景。

首先在资源中添加画笔。 例如:

<Window.Resources>
    <ImageBrush x:Key="MyImageBrush"
                ImageSource="C:\Test.png" />
</Window.Resources>

然后只需使用StaticResource在特定触发器中设置它。

    <DataTemplate x:Key="DataTemplate_Level2">
        <Label Content="{Binding }"
               Width="70"
               Height="70"
               HorizontalContentAlignment="Center"
               x:Name="Background">
        </Label>
        <DataTemplate.Triggers>
            <DataTrigger Binding="{Binding}"
                         Value="7">
                <Setter TargetName="Background"
                        Property="Background"
                        Value="{StaticResource MyImageBrush}" />
            </DataTrigger>
        </DataTemplate.Triggers>
    </DataTemplate>