c# - 如何根据其属性更改自定义控件的背景颜色

标签 c# wpf xaml custom-controls

我有一个简单的自定义控件,可以向用户显示一条消息(类似于浏览器的信息栏)。

我添加了一个指示错误消息的 bool 依赖属性。如果设置了标志,则控件的背景颜色应为红色,否则为黄色。

这是控件的样式(在 Themes\Generic.xaml 中):

<Style TargetType="{x:Type local:InfoBar}">
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="{x:Type local:InfoBar}">
                <ControlTemplate.Triggers>
                    <Trigger Property="IsError" Value="True" >
                             <Setter Property="Background" Value="LightPink" />
                    </Trigger>
                    <Trigger Property="IsError" Value="False" >
                             <Setter Property="Background" Value="LightYellow" />
                    </Trigger>                  
                </ControlTemplate.Triggers>

                <Grid Margin="4,0,4,0">
                    <Grid.ColumnDefinitions>
                        <ColumnDefinition Width="*" />
                        <ColumnDefinition Width="auto" />
                    </Grid.ColumnDefinitions>
                    <TextBlock Text="{TemplateBinding Message}" Padding="5" FontWeight="Normal" TextWrapping="Wrap" Grid.Column="0"/>
                    <Button x:Name="PART_CloseButton" Grid.Column="1" VerticalAlignment="Top"  >
                        <Button.Template>
                            <ControlTemplate>
                                <Border HorizontalAlignment="Center" VerticalAlignment="Center" BorderBrush="Transparent">
                                    <Image Height="16" Width="16" Source="/QOffice.Common.Controls;component/Images/icons/Close.png"  />
                                </Border>
                            </ControlTemplate>
                        </Button.Template>
                    </Button>
                </Grid>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>

这是控件本身:

[TemplatePart(Name = PART_CloseButton, Type = typeof(ButtonBase))]
public class InfoBar : Control
{

    private const string PART_CloseButton = "PART_CloseButton";

    static InfoBar()
    {
        DefaultStyleKeyProperty.OverrideMetadata(typeof(InfoBar), new FrameworkPropertyMetadata(typeof(InfoBar)));

    }

    #region CloseButton

    private ButtonBase _closeButton;
    /// <summary>
    /// Gets or sets the CloseButton template part.
    /// </summary>
    private ButtonBase CloseButton
    {
        get
        {
            return _closeButton;
        }
        set
        {
            if (_closeButton != null)
            {
                _closeButton.Click -= OnButtonClick;
            }

            _closeButton = value;

            if (_closeButton != null)
            {
                _closeButton.Click += OnButtonClick;
            }
        }
    }

    private void OnButtonClick(object sender, RoutedEventArgs e)
    {
        this.Visibility = System.Windows.Visibility.Collapsed;
    }


    #endregion 


    public override void OnApplyTemplate()
    {
        CloseButton = GetTemplateChild(PART_CloseButton) as ButtonBase;


    }


    #region DependencyProperty Message of InfoBar

    public string Message
    {
        get { return (string)GetValue(MessageProperty); }
        set { SetValue(MessageProperty, value); }
    }

    public static readonly DependencyProperty MessageProperty =
        DependencyProperty.Register("Message", typeof(string), typeof(InfoBar),
                new UIPropertyMetadata());

    #endregion


    #region DependencyProperty IsError of InfoBar

    public bool IsError
    {
        get { return (bool)GetValue(IsErrorProperty); }
        set { SetValue(IsErrorProperty, value); }
    }

    public static readonly DependencyProperty IsErrorProperty =
        DependencyProperty.Register("IsError", typeof(bool), typeof(InfoBar),
                new UIPropertyMetadata());

    #endregion





}

如您所见,我已经定义了一个属性 IsError 和一个触发器来设置控件的背景。

但是背景总是透明的。除此之外,控制功能是否正常。

怎么了?

最佳答案

即使我手动添加背景颜色,您的自定义控件似乎也没有正确设置背景颜色。我不确定这是为什么,希望有人能详细说明。我确实通过使用以下方法更改您样式中的网格颜色来解决您的问题:

<Grid.Style>
    <Style TargetType="{x:Type Grid}">
        <Style.Triggers>
            <DataTrigger Binding="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type local:InfoBar}}, Path=IsError}" Value="True">
                <Setter Property="Background" Value="LightPink" />
            </DataTrigger>
            <DataTrigger Binding="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type local:InfoBar}}, Path=IsError}" Value="False">
                <Setter Property="Background" Value="LightYellow" />
            </DataTrigger>
        </Style.Triggers>
    </Style>
</Grid.Style>

这会根据 InfoBar 控件中的 IsError 值触发网格的背景色。

关于c# - 如何根据其属性更改自定义控件的背景颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11654409/

相关文章:

c# - 实现通用接口(interface)的问题

c# - HttpContext.RequestServices.GetService<T>() 与 services.AddScope<T>()?

c# - 在 c# 中用 %20 转换/替换空格,反之亦然

c# - BitmapImage:如何在返回图像之前等待 BitmapImage 初始化? (C#.NET)

c# - 为什么我的 WPF TextBox 不显示任何字符?

wpf - 在样式中声明文本装饰,例如下划线、删除线

c# - 在 XAML 中更改 Slider 的值引发异常

c# - 可以将整个对象绑定(bind)到 XAML 中的 CommandParameter 吗?

c# - 如何在 C# 中使用 <T> 魔法使方法返回任意结构?

xaml - 添加 Pivot 和其他 Microsoft.Phone 控件时,Visual Studio 2012 XAML UI 设计器引发异常