属性在代码隐藏中具有默认值 - WPF

时间:2018-03-29 12:17:36

标签: c# wpf xaml properties dependency-properties

我正在使用一些UserControls自动"注册"在主窗口的字典中。 UserControls在主窗口的XAML中设置了一些值 我已经实现了依赖属性以及所有这些,工作正常。 但是,当我从

等自定义属性访问值时
Main.Conn.RequestStatus(sf.Address);

该属性返回我在类definiton中设置的默认值。

public string Address {get; set;} = "";

但是当我打电话时

Main.Conn.RequestStatus((string)GetValue(AddressProperty)));

它正常工作(地址为" 1/11")。

为什么?我是否必须使用Dependecy Property方法获取属性值?或者我是否以错误的方式实现了属性?

1 个答案:

答案 0 :(得分:1)

声明

public string Address {get; set;} = "";

不是依赖项属性的有效包装器。

它必须如下所示:

public string Address
{
    get { return (string)GetValue(AddressProperty); }
    set { SetValue(AddressProperty, value); }
}

依赖项属性标识符字段应该像这样定义:

public static readonly DependencyProperty AddressProperty =
    DependencyProperty.Register(
        nameof(Address),
        typeof(string),
        typeof(YourControl),
        new PropertyMetadata(""));