在用户控件样式中设置依赖属性

3

我实现了一个用户控件,其中包含一个依赖属性,如下所示:

public partial class MyUC : UserControl, INotifyPropertyChanged
{
    public static readonly DependencyProperty MyBackgroundProperty =
        DependencyProperty.Register("MyBackground", typeof(Brush), typeof(MyUC), 
            new FrameworkPropertyMetadata(Brushes.White, 
                FrameworkPropertyMetadataOptions.AffectsRender));

    public Brush MyBackground
    {
        get { return (Brush)GetValue(MyBackgroundProperty); }
        set { SetValue(MyBackgroundProperty, value); }
    }

    //...
}

尝试在XAML中设置此属性,如下所示:

<UserControl x:Class="Custom.MyUC"
         x:Name="myUCName"
         xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
         xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
         xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
         xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
         xmlns:local="clr-namespace:Custom"
         mc:Ignorable="d"
         TabIndex="0" KeyboardNavigation.TabNavigation="Local" 
         HorizontalContentAlignment="Left" VerticalContentAlignment="Top" 
         MouseLeftButtonDown="OnMouseLeftButtonDown"> 
    <UserControl.Style>
        <Style TargetType="local:MyUC">      
            <Setter Property="MyBackground" Value="Black"/>
        </Style>
    </UserControl.Style>   

    <Border BorderThickness="0">
        //...
    </Border>
</UserControl>

我的代码已经编译成功了,但在运行应用程序时出现了以下异常:

设置属性 'System.Windows.Setter.Property' 时引发异常。" 行号 '..' 和行位置 '..'."

我该如何解决这个问题?

1个回答

1
问题出现的原因是您试图将TargetType="MyUC"的样式应用于UserControl类型的元素。
解决方案是从控件外部应用样式。例如,当您在另一个窗口中使用该控件时:
<Window.Resources>
    <Style TargetType="local:MyUC">
        <Setter Property="MyBackground" Value="Red" />
    </Style>
</Window.Resources>
<Grid>
    <local:MyUC />
</Grid>

作为测试,我将此代码添加到用户控件中:
public partial class MyUC
{
    public MyUC()
    {
        InitializeComponent();
    }   

    public static readonly DependencyProperty MyBackgroundProperty =
        DependencyProperty.Register("MyBackground", typeof(Brush), typeof(MyUC), 
        new PropertyMetadata(Brushes.White, PropertyChangedCallback));

    private static void PropertyChangedCallback(DependencyObject dependencyObject, 
        DependencyPropertyChangedEventArgs dependencyPropertyChangedEventArgs)
    {
        ((MyUC)dependencyObject).MyBackgroundPropertyChanged(
            (Brush)dependencyPropertyChangedEventArgs.NewValue);
    }

    private void MyBackgroundPropertyChanged(Brush newValue)
    {
        Background = newValue;
    }

    public Brush MyBackground
    {
        get { return (Brush)GetValue(MyBackgroundProperty); }
        set { SetValue(MyBackgroundProperty, value); }
    }
}

这将导致控件具有红色背景。

1
嗨Phil,非常感谢你的回答。有没有另一种更面向对象的解决方案?例如,我尝试根据由MyUC管理的数据触发器来设置属性MyBackground。这应该在MyUC的代码中完成,而不是每个使用MyUC的应用程序中单独实现。 - Waterman

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接