c# - 如何声明一个也可以在没有绑定的情况下设置的 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));
我声明了这个新属性,但我仍然无法绑定任何东西,只接受原始值
解决方案
您不应该在回调中创建新绑定。事实上,您根本不需要任何回调。
将依赖属性重命名为“Text”之类的更好的名称,并将属性绑定Text
到StringBox
依赖属性的当前值,如下所示:
<TextBox x:Name="StringBox"
Text="{Binding Text, RelativeSource={RelativeSource AncestorType=local:NotEmptyStringTextBox},
UpdateSourceTrigger=PropertyChanged}" />
然后,您可以像往常一样设置或绑定依赖项属性。
如果你真的想要一个“PropertyPath”属性,它不应该是一个可以绑定某些东西的依赖属性,而应该是一个简单的 CLR 属性,你可以将它设置为string
表示要绑定到的属性的名称。
例如,这是如何实现DisplayMemberPath
an 的属性的ItemsControl
。
推荐阅读
- database - Oracle 12c 无法使用 sqlplus 连接数据库
- java - 复制后 Amazon S3 Java SDK copyObject 权限被拒绝
- r - 卸载 R 包并释放内存
- java - 当我的查询满足预期条件时,如何使用 JSON PATH 获取整个 json 对象
- angular - 使用 rxjs 对添加到 Firestore 集合的自定义属性进行排序/分组
- javascript - 我想在 html 页面中添加弹出窗口。示例位于 www.pu.edu.pk(在线录取)
- html - 为什么最小高度将 div 拉伸到页面的全长?
- arrays - 在 go 中删除或调整数组大小
- python - JetBrains 中的 Python 2 类型代码完成?
- google-chrome-extension - 在安装后出现的弹出窗口中更改默认文本