XAML 嵌套的UserControl引发“属性已由注册”

flvlnr44  于 2023-01-28  发布在  其他
关注(0)|答案(1)|浏览(166)

我有这个用户控件xaml:

<Grid>
        <Separator x:Name="sep" VerticalAlignment="Center" Height="10" />
</Grid>

以及我定义DependencyProperty来编辑线条颜色的代码:

public partial class SeparatorLineText : UserControl
    {
        public static DependencyProperty? ColorProperty;
        private PropertyMetadata meta = new PropertyMetadata(propertyChangedCallback: ColorChanged);
        public SeparatorLineText()
        {
            ColorProperty = DependencyProperty.Register("MyColor", 
                typeof(Brush), 
                typeof(SeparatorLineText), 
                meta);

            InitializeComponent();
        }

        public Brush MyColor
        {
            get { return (Brush)base.GetValue(ColorProperty); }
            set { base.SetValue(ColorProperty, value); }
        }

        private static void ColorChanged(object d, DependencyPropertyChangedEventArgs e)
        {
            ((SeparatorLineText)d).OnColorChanged(e);
        }

        protected virtual void OnColorChanged(DependencyPropertyChangedEventArgs e)
        {
            sep.Background = (Brush)e.NewValue;
        }
    }

然后我有另一个UserControl,里面有SeparatorLineText:

<UserControl x:Class="MySubWindow" 
...
>

<Grid>
    <control:SeparatorLineText MyColor="Red"/>
</Grid>

最后,在MainWindow.xaml中,我包含了MySubWindow,它里面有分隔符行文本:

<control:MySubWindow x:Name="MyTab" VerticalAlignment="Top" Width="1280"/>

当我运行项目时,它正确显示了我的自定义分隔符,但在主窗口的xaml设计器中,它没有正确加载,显示:“*MyColor属性已由SeparatorLineText注册 *”
我已经阅读了关于这个问题的其他主题,但我没有找到解决方案。

brc7rcf0

brc7rcf01#

依赖项属性只需要注册一次。在您的情况下,它在每次调用构造函数时都要注册。您可以使用静态构造函数来解决这个问题:

public static DependencyProperty ColorProperty;

// You can also make this field static, since it is not bound to a specific instance.
private static PropertyMetadata meta = new PropertyMetadata(propertyChangedCallback: ColorChanged);

static SeparatorLineText()
{
    ColorProperty = DependencyProperty.Register("MyColor", 
        typeof(Brush), 
        typeof(SeparatorLineText), 
        meta);
}

public SeparatorLineText()
{
    InitializeComponent();
}

或者直接初始化:

public static DependencyProperty ColorProperty = 
    DependencyProperty.Register("MyColor", 
        typeof(Brush), 
        typeof(SeparatorLineText), 
        meta);

// You can also make this field static, since it is not bound to a specific instance.
private static PropertyMetadata meta = new PropertyMetadata(propertyChangedCallback: ColorChanged);

public SeparatorLineText()
{
    InitializeComponent();
}

相关问题