首页 > Windows开发 > 详细

WPF DataTrigger 改变控件颜色

时间:2021-09-16 12:13:01      阅读:40      评论:0      收藏:0      [点我收藏+]

之前这篇博文WPF 做一个指示灯,用 TrueFalse两种情况来进行判断,其实也可以用 int 类型进行多个条件的判断。

技术分享图片

XAML:

<Window.DataContext>
    <local:TestVM/>
</Window.DataContext>

<Grid>
    <StackPanel Orientation="Horizontal" HorizontalAlignment="Center">
        <Ellipse Width="50" Height="50">
            <Ellipse.Style>
                <Style TargetType="Ellipse">
                    <Style.Triggers>
                        <DataTrigger Binding="{Binding PresentColor}" Value="0">
                            <Setter Property="Shape.Fill" Value="Orange"/>
                        </DataTrigger>
                        <DataTrigger Binding="{Binding PresentColor}" Value="1">
                            <Setter Property="Shape.Fill" Value="Green"/>
                        </DataTrigger>
                        <DataTrigger Binding="{Binding PresentColor}" Value="2">
                            <Setter Property="Shape.Fill" Value="Red"/>
                        </DataTrigger>
                    </Style.Triggers>
                </Style>
            </Ellipse.Style>
        </Ellipse>
        <Button Content="换色" Command="{Binding ChangeColorCommand}" Margin="10 0 0 0" Height="30" Width="80"/>
    </StackPanel>        
</Grid>

ViewModel:

public class TestVM : ViewModelBase
{
    private int _PresentColor = 0;
    public int PresentColor
    {
        get { return _PresentColor; }
        set { _PresentColor = value; RaisePropertyChanged(nameof(PresentColor)); }
    }

    private RelayCommand _changeColorCommand;
    public RelayCommand ChangeColorCommand
    {
        get {
            if (_changeColorCommand == null)
                _changeColorCommand = new RelayCommand(ChangeColor);
            return _changeColorCommand; }
        set { _changeColorCommand = value; RaisePropertyChanged(nameof(ChangeColorCommand)); }
    }


    private void ChangeColor()
    {
        if (PresentColor < 2)
            PresentColor++;
        else
            PresentColor = 0;
    }
}

WPF DataTrigger 改变控件颜色

原文:https://www.cnblogs.com/huvjie/p/15265426.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!