【问题标题】:WPF DependencyProperty UsageWPF DependencyProperty 用法
【发布时间】:2014-02-26 23:46:36
【问题描述】:

我很难让依赖属性正常工作而不会导致编译错误。

我有一个名为 TitleBar 的用户控件,其中包含此 DependencyProperty:

public static readonly DependencyProperty TitleProperty = DependencyProperty.Register("Title", typeof(string), typeof(TitleBar), new PropertyMetadata(false));

    public string Title
    {
        get
        {
            return (string)GetValue(TitleProperty);
        }
        set
        {
            SetValue(TitleProperty, value);
        }
    }

在我看来,在 xaml 中:

<Components:TitleBar x:Name="customTitleBar" Grid.Column="0" Grid.Row="0" Grid.ColumnSpan="3"/>

导致设计器/编译错误:

Cannot create an instance of "TitleBar". ... The invocation of the constructor on type 'TitleBar' that matches the specified binding constraints threw an exception. System.Exception {System.Windows.Markup.XamlParseException}

用户控件可以在没有 DP 的情况下完美运行。我做错了什么?

奇怪的是,当我实际将 Title="..." 属性放入 xaml 时,它在设计器中工作,直到我尝试编译它。从那时起,它给了我提到的错误。

【问题讨论】:

    标签: c# wpf xaml properties


    【解决方案1】:

    您的DependencyPropertystring 但在PropertyMetadata 中您将默认值指定为false

    【讨论】:

    【解决方案2】:

    当属性类型为string时,您已将默认值指定为bool

    改变

    new PropertyMetadata(false)
    

    new PropertyMetadata(null)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-03-22
      • 2012-10-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多