首页 > 解决方案 > 如何声明一个也可以在没有绑定的情况下设置的 DependencyProperty

问题描述

我知道我可以这样声明一个新的 DependencyProperty:

public String PropertyPath
{
    get { return (String)GetValue(PropertyPathProperty); }
    set { SetValue(PropertyPathProperty, value); }
}

public static readonly DependencyProperty PropertyPathProperty =
    DependencyProperty.Register(nameof(PropertyPath), typeof(String),
        typeof(NotEmptyStringTextBox),
        new FrameworkPropertyMetadata(PropertyPath_PropertyChanged));

protected static void PropertyPath_PropertyChanged(DependencyObject d,
    DependencyPropertyChangedEventArgs e)
{
    var ctl = d as NotEmptyStringTextBox;

    var binding = new Binding(ctl.PropertyPath)
    {
        ValidationRules = { new NotEmptyStringRule() },

        //  Optional. With this, the bound property will be updated and validation 
        //  will be applied on every keystroke. 
        UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged
    };

    ctl.StringBox.SetBinding(TextBox.TextProperty, binding);

}

但是随后 UserControl 只能接收到一个带有要绑定的属性名称的字符串,并绑定到它。

我想要的是能够拥有与“经典”属性相同的行为,您可以绑定到这些属性,也可以提供一个静态值。我的用法是修改 UserControl 的显示状态的布尔值,无论是静态地使用固定值还是动态地使用绑定,都取决于用例。

也许我一开始创建依赖属性的方式不正确,但这是我可以使用它的方法:

<inputboxes:NotEmptyStringTextBox 
                Grid.Column="1"
                PropertyPath="Name"/>

这将从 DataContext 绑定“名称”属性,但我不能将它与原始字符串一起使用,因为它会产生 BindingExpression 错误:“找不到属性”

编辑:我现在尝试了以下方法:

public bool Test
{
    get { return (bool)GetValue(TestProperty); }
    set { SetValue(TestProperty, value); }
}

public static readonly DependencyProperty TestProperty =
    DependencyProperty.Register(nameof(Test), typeof(bool),
        typeof(DamageTemplateListEditableUserControl));

我声明了这个新属性,但我仍然无法绑定任何东西,只接受原始值

标签: c#wpfxamldependency-properties

解决方案


您不应该在回调中创建新绑定。事实上,您根本不需要任何回调。

将依赖属性重命名为“Text”之类的更好的名称,并将属性绑定TextStringBox依赖属性的当前值,如下所示:

<TextBox x:Name="StringBox"
    Text="{Binding Text, RelativeSource={RelativeSource AncestorType=local:NotEmptyStringTextBox},
        UpdateSourceTrigger=PropertyChanged}" />

然后,您可以像往常一样设置或绑定依赖项属性。

如果你真的想要一个“PropertyPath”属性,它不应该是一个可以绑定某些东西的依赖属性,而应该是一个简单的 CLR 属性,你可以将它设置为string表示要绑定到的属性的名称

例如,这是如何实现DisplayMemberPathan 的属性的ItemsControl


推荐阅读