WPF - 更改背景按钮

时间:2016-09-09 04:39:19

标签: wpf

我想使用绑定更改背景颜色。当我不使用Style="{DynamicResource ButtonStyle}"时,背景会发生变化。这是我的代码:

<Button Style="{DynamicResource ButtonStyle}" Content="{Binding Title, UpdateSourceTrigger=PropertyChanged}" 
                        Command="{Binding RelativeSource={RelativeSource AncestorType={x:Type ItemsControl}}, Path=DataContext.SelectButton}"
                        CommandParameter="{Binding}" ToolTip="{Binding Description}">
                    <Button.Resources>
                        <Style TargetType="{x:Type Button}">
                            <Style.Triggers>
                                <DataTrigger Binding="{Binding IsSelected, UpdateSourceTrigger=PropertyChanged}" Value="True">
                                    <Setter Property="Background" Value="Red"></Setter>
                                </DataTrigger>

                                <DataTrigger Binding="{Binding IsSelected, UpdateSourceTrigger=PropertyChanged}" Value="False">
                                    <Setter Property="Background" Value="Blue"></Setter>
                                </DataTrigger>
                            </Style.Triggers>
                        </Style>
                    </Button.Resources>
                </Button>

如何使用触发器更改按钮中的背景颜色?可以作为插入样式引用的触发器吗?

1 个答案:

答案 0 :(得分:2)

如果无法将触发器应用于按钮或样式的控件模板,则可以使用值转换器而不是样式。

<Style x:Key="ButtonStyle2" TargetType="{x:Type Button}">
    <Style.Triggers>
        <DataTrigger Binding="{Binding IsSelected}" Value="True">
            <Setter  Property="Background" Value="Red"/>
        </DataTrigger>
        <DataTrigger Binding="{Binding IsSelected}" Value="False">
            <Setter Property="Background" Value="Blue"/>
        </DataTrigger>
    </Style.Triggers>
</Style>

或使用样式

<Style x:Key="ButtonStyle1" TargetType="{x:Type Button}">
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="{x:Type Button}">
                <Grid x:Name="myGrid" Width="200" Height="20" Background="{TemplateBinding Background}">
                </Grid>
                <ControlTemplate.Triggers>
                    <DataTrigger Binding="{Binding IsSelected}" Value="True">
                        <Setter TargetName="myGrid" Property="Background" Value="Red"/>
                    </DataTrigger>
                    <DataTrigger Binding="{Binding IsSelected}" Value="False">
                        <Setter TargetName="myGrid" Property="Background" Value="Blue"/>
                    </DataTrigger>
                </ControlTemplate.Triggers>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>

或控制模板

tns --version