【问题标题】:Adding dependency property to custom control causes strange errors to occur to style将依赖属性添加到自定义控件会导致样式出现奇怪的错误
【发布时间】:2023-03-29 09:58:01
【问题描述】:

我正在尝试创建一个从 ListBoxItem 扩展的自定义控件,如下所示:

public class MainNavListBoxItem : ListBoxItem
{
    public MainNavListBoxItem()
    {
        this.DefaultStyleKey = typeof(MainNavListBoxItem);
    }
}

我的样式在 ResourceDictionary 中定义如下:

<Style TargetType="assets:MainNavListBoxItem">
        <Setter Property="Padding" Value="3"/>
        <Setter Property="HorizontalContentAlignment" Value="Left"/>
        <Setter Property="VerticalContentAlignment" Value="Top"/>
        <Setter Property="Background" Value="Transparent"/>
        <Setter Property="BorderThickness" Value="1"/>
        <Setter Property="TabNavigation" Value="Local"/>
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="assets:MainNavListBoxItem">
                    <Grid Height="50">
                        <VisualStateManager.VisualStateGroups>
...

现在它像这样编译并运行良好,但是一旦我向 MainNavListBoxItem 类添加额外的依赖属性,我就会开始收到这样的错误:

无法从文本“Padding”创建“System.Windows.DependencyProperty”。

如果我在样式中重新排列 Setter 标签,它总是会报告最上面的标签。

以及我的依赖属性代码供参考:

public ImageSource ImageDark
{
    get { return (ImageSource)GetValue(ImageDarkProperty); }
    set { SetValue(ImageDarkProperty, value); }
}
public static readonly DependencyProperty ImageDarkProperty =
    DependencyProperty.Register("ImageDark", typeof(ImageSource), typeof(MainNavListBoxItem), new PropertyMetadata(0));

这是怎么回事?!我希望能够在样式中使用这个 ImageDark 依赖属性!

我已经对此错误进行了大量搜索,但似乎与此问题无关。

【问题讨论】:

  • 未经测试不确定是否相关,但您指定默认样式键的方式异常。您应该覆盖静态构造函数中的元数据。在您的实例构造函数中执行此操作可能会使 WPF 混淆。例如,请参阅here
  • 你不能覆盖 silverlight 中的元数据,可以吗?
  • 抱歉,我以为这是 WPF。
  • 您的 PropertyMetadata 指定 ImageSource 的默认值为零??
  • 这就是问题所在。甚至没有注意到我没有将其更改为“null”。发布为答案,我会接受它

标签: c# .net silverlight xaml


【解决方案1】:

这个问题是因为我忘记将我的依赖属性中的new PropertyMetadata(0) 更改为new PropertyMetadata(null)。谢谢肯特。

【讨论】:

    猜你喜欢
    • 2010-11-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-08-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-05-26
    相关资源
    最近更新 更多