如何声明也可以在不绑定的情况下设置的依赖项属性



我知道我可以这样声明一个新的依赖属性:

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 的"Name"属性,但我不能将其与原始字符串一起使用,因为它会产生 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));

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

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

将依赖项属性重命名为更好的名称,例如"Text",只需将StringBoxText属性绑定到依赖项属性的当前值,如下所示:

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

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

如果确实需要"PropertyPath"属性,则它不应是可以绑定某些内容的依赖项属性,而应是可以设置为表示要绑定到的属性名称的string的简单 CLR 属性。

例如,这是实现ItemsControlDisplayMemberPath属性的方式。

最新更新