样式触发DependencyProperty的子属性

时间:2015-04-08 15:54:06

标签: c# .net wpf xaml

我想要设置一个控件,具体取决于该控件的自定义MessageType类型Message的设置DependencyProperty

自定义类型:

public class Message : ObservableObject
{
    public MessageTypes MessageType
    {
        get { return _messageType; }
        set {
            RaisePropertyChanged(() => MessageType);
            _messageType = value;
        } 
    }

    public string Text { ... }

    ...
}

控制:

public class MessageControl : Control
{
    public static readonly DependencyProperty MessageProperty =
        DependencyProperty.Register(
            "Message",
            typeof(Message),
            typeof(MessageControl),
            new FrameworkPropertyMetadata(null,
                FrameworkPropertyMetadataOptions.BindsTwoWayByDefault));

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

样式:

<ControlTemplate x:Key="MessageControlTemplate"
                 TargetType="controls:MessageControl">
    <Border Background="{TemplateBinding Background}">
        <TextBlock Text="{Binding Path=Message.Text,
                             RelativeSource={RelativeSource TemplatedParent}}" />
    </Border>
</ControlTemplate>

<Style TargetType="controls:MessageControl">
    <Setter Property="Template"
            Value="{StaticResource MessageControlTemplate}" />

    <Style.Triggers>
        <!-- HERE IS THE ISSUE -->
        <Trigger Property="Message.MessageType"
                 Value="{x:Static classes:MessageType.Error}">
            <Setter Property="Background" Value="Red" />
        </Trigger>
    </Style.Triggers>
</Style>

所以问题是我无法为Message.MessageType(或基本上任何其他子属性)添加触发器。

甚至可以实现这一目标吗?或者我应该在MessageControlText的{​​{1}}中创建两个属性吗?

1 个答案:

答案 0 :(得分:2)

您可以使用DataTrigger执行此操作:

<Style TargetType="controls:MessageControl">
    ...
    <Style.Triggers>
        <DataTrigger Binding="{Binding Message.MessageType,
                               RelativeSource={RelativeSource Self}}"
                     Value="{x:Static classes:MessageType.Error}">
            <Setter Property="Background" Value="Red" />
        </DataTrigger>
    </Style.Triggers>
</Style>

在设置属性的支持字段后,您还应该引发PropertyChanged事件:

public MessageType MessageType
{
    get { return _messageType; }
    set
    {
        _messageType = value;
        RaisePropertyChanged(() => MessageType);
    }
}