如何根据滑块值WPF更新按钮背景颜色

时间:2017-03-15 11:16:46

标签: wpf

WPF: 

<Grid>
     <Button Panel.ZIndex="-5" Background="{Binding CardColour}"></Button>
     <Slider x:Name="HomeCardSlider"   Height="30" Width="25" Maximum="2" SmallChange="1" Orientation="Vertical" Value="{Binding CardState}" HorizontalAlignment="Right" VerticalAlignment="Center" BorderBrush="#FFF94F0F">
     </Slider>
 </Grid>

班级:

public class LiveComm
{  
    public int CardState { get; set; }
    public string CardColour { get; set; }
}

我正在尝试根据滑块值更新按钮的颜色。如果值为0,则按钮颜色为灰色,1为黄色,2为红色。

1 个答案:

答案 0 :(得分:2)

具有少量状态(0,1,2),可以通过触发器在没有视图模型的情况下完成。按钮样式中的触发器跟踪滑块值并根据它更改背景。

<Button Panel.ZIndex="-5">
    <Button.Style>
        <Style TargetType="Button">
            <Setter Property="Background" Value="Gray"/>
            <Style.Triggers>
                <DataTrigger Binding="{Binding Path=Value, ElementName=HomeCardSlider}" 
                             Value="1">
                    <Setter Property="Background" Value="Yellow"/>
                </DataTrigger>

                <DataTrigger Binding="{Binding Path=Value, ElementName=HomeCardSlider}" 
                             Value="2">
                    <Setter Property="Background" Value="Red"/>
                </DataTrigger>
            </Style.Triggers>
        </Style>
    </Button.Style>
</Button>
<Slider x:Name="HomeCardSlider" 
        IsSnapToTickEnabled="True"
        Height="30" Width="25" 
        Maximum="2" SmallChange="1" 
        Orientation="Vertical"
        HorizontalAlignment="Right" VerticalAlignment="Center" BorderBrush="#FFF94F0F">
</Slider>

请注意,我为Slider设置了IsSnapToTickEnabled="True",否则可以获得非整数值