UserControl触发器的自定义属性

时间:2012-02-26 17:42:31

标签: wpf triggers dependencies styles custom-properties

我正在编写一个名为MyUserControl的自定义用户控件。我有很多DependecyProperties,我在MainWindow中使用它,多次定义了几个MyUserControl。我想知道的是如何创建样式的触发器/属性将触发的自定义属性?

例如,如果我有自定义属性BOOL IsGoing和自定义属性MyBackgroung(UserControl的背景),则定义为:

public bool IsGoing
    {
        get { return (bool)this.GetValue(IsGoingProperty); }
        set { this.SetValue(IsGoingProperty, value); }
    }
    public static readonly DependencyProperty IsGoingProperty = DependencyProperty.RegisterAttached(
        "IsGoing", typeof(bool), typeof(MyUserControl), new PropertyMetadata(false));  

public Brush MyBackground
    {
        get { return (Brush)this.GetValue(MyBackgroundProperty); }
        set { this.SetValue(MyBackgroundProperty, value); }
    }
    public static readonly DependencyProperty MyBackgroundProperty = DependencyProperty.Register(
            "MyBackground", typeof(Brush), typeof(MyUserControl), new PropertyMetadata(Brushes.Red));

如果我在MainWindow.xaml中定义我的UserControl,我如何访问触发器并设置MyBackground,具体取决于IsGoing属性是否为true / false? 我尝试了很多东西,但实际上,我正在尝试实现类似的东西:

<custom:MyUserControl MyBackground="Green" x:Name="myUC1" Margin="120.433,0,0,65.5" Height="50" Width="250" VerticalAlignment="Bottom" HorizontalAlignment="Left"  >
        <Style>
            <Style.Triggers>
                <Trigger Property="IsGoing" Value="True">
                    <Setter Property="MyBackground" Value="Yellow"/>
                </Trigger>
            </Style.Triggers>
        </Style>
    </custom:MyUserControl>

我希望我的解释足够让你理解。我一直在研究这个问题几天,我似乎无法找到解决方案。 谢谢你的帮助!!!

阿德里安

1 个答案:

答案 0 :(得分:3)

您的样式应该只需要用作UserControl.Style并且具有正确的TargetType,并且由于precedence而需要通过触发器更改的默认值也需要移动到样式中:

<custom:MyUserControl.Style>
    <Style TargetType="custom:MyUserControl">
        <Setter Property="MyBackground" Value="Green"/>
        <Style.Triggers>
            <Trigger Property="IsGoing" Value="True">
                <Setter Property="MyBackground" Value="Yellow"/>
            </Trigger>
        </Style.Triggers>
    </Style>
</custom:MyUserControl.Style>

这实际是否取决于您在控件定义中如何使用属性。

相关问题