我使用如下所示的依赖属性实现了一个用户控件:
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”引发异常。行号'..'和行位置'..'。”
我该如何解决这个问题?