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

时间:2013-04-05 14:30:42

标签: wpf xaml styles controls

我实现了一个带有依赖项属性的用户控件,如下所示:

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 个答案:

答案 0 :(得分: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); }
    }
}

然后导致控件具有红色背景。

相关问题