问题描述
我知道我可以这样声明一个新的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的“ 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
的{{1}}属性绑定到依赖项属性的当前值,如下所示:
StringBox
然后您可以照常设置或绑定依赖项属性。
如果您确实想要“ PropertyPath”属性,那么它不应该是可以绑定某些内容的依赖项属性,而是可以设置为表示的<TextBox x:Name="StringBox"
Text="{Binding Text,RelativeSource={RelativeSource AncestorType=local:NotEmptyStringTextBox},UpdateSourceTrigger=PropertyChanged}" />
的简单CLR属性。要绑定的属性的名称。
例如,这是string
的{{1}}属性的实现方式。