WPF 做一个指示灯

XAML:

 <StackPanel VerticalAlignment="Center" HorizontalAlignment="Center"  Orientation="Horizontal">

    <Ellipse Width="40" Height="40"  VerticalAlignment="Center">
        <Ellipse.Style>
            <Style TargetType="Ellipse">
                <Style.Triggers>
                    <DataTrigger Binding="{Binding PresentColor}" Value="True">
                        <Setter Property="Shape.Fill" Value="Red"/>
                    </DataTrigger>
                    <DataTrigger Binding="{Binding PresentColor}" Value="False">
                        <Setter Property="Shape.Fill" Value="Gray"/>
                    </DataTrigger>
                </Style.Triggers>
            </Style>
        </Ellipse.Style>
    </Ellipse>
    <local:HButton Content="更改颜色" Height="30" Width="80" Margin="10 0 0 0" x:Name="clk" Command="{Binding ChangeColorCommand}"/>

</StackPanel>

注意:不要再在<Ellipse/> 里面设定 Fill 属性,因为这样会把样式中的 Fill 属性覆盖掉。

ViewModel:

private bool _presentColor = false;
public bool PresentColor
{
    get { return _presentColor; }
    set { _presentColor = value; RaisePropertyChanged(nameof(PresentColor)); }
}

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

private void ChangeColor()
{
    PresentColor = !PresentColor;
}

点击按钮,圆型颜色在灰色和红色切换:

如何让按钮颜色一起更改呢?

XAML 中按钮背景颜色绑定 ViewModel 中的一个颜色值。

XAML 中更改:

<local:HButton Content="更改颜色" Background="{Binding ColorForBtn}" Height="30" Width="80" Margin="10 0 0 0" x:Name="clk" Command="{Binding ChangeColorCommand}"/>

ViewModel 中增加/更改:

private SolidColorBrush _colorForBtn = new SolidColorBrush(Colors.Gray);
public SolidColorBrush ColorForBtn
{
    get { return _colorForBtn; }
    set { _colorForBtn = value; RaisePropertyChanged(nameof(ColorForBtn)); }
}

private void ChangeColor()
{
    PresentColor = !PresentColor;

    if (PresentColor)
    {
        ColorForBtn = new SolidColorBrush(Colors.Red);
    }
    else
    {
        ColorForBtn = new SolidColorBrush(Colors.Gray);
    }
}

其实,也可以用 DataTrigger 触发器做,像上面的 Ellipse 一样,绑定到 PresentColor 这个属性上去。这样转换的逻辑在界面完成,不用单独多写后台代码逻辑。

posted @ 2021-08-10 09:14  double64  阅读(3354)  评论(3编辑  收藏  举报