【发布时间】:2014-08-26 18:41:16
【问题描述】:
我有一个具有简单依赖属性的类,它是在 Visual Studio 中的 propdp sn-p 的帮助下编写的。我从TextBox 派生了这个类,并给了它一个我想成为依赖属性的PrePend 属性。我想要这样,如果用户将PrePend 设置为“Hello”并将Text 设置为“World”,Text getter 将返回“Hello World”。我的问题是代码似乎忽略了我的 PrePend 依赖属性。
我的课在这里:
internal class MyTextBox : TextBox
{
public new string Text
{
get { return this.PrePend + base.Text; }
set { base.Text = value; }
}
public string PrePend
{
get { return (string)GetValue(PrePendProperty); }
set { SetValue(PrePendProperty, value); }
}
// Using a DependencyProperty as the backing store for PrePend.
// This enables animation, styling, binding, etc...
public static readonly DependencyProperty PrePendProperty =
DependencyProperty.Register("PrePend", typeof(string),
typeof(MyTextBox), new PropertyMetadata(""));
}
我通过使用propdp sn-p 获得了此代码。我只添加了Text setter。
我的XAML 代码是这样的:
<local:MyTextBox PrePend="Hello " Text="World" />
当我运行代码时,屏幕显示“世界”。我在Text getter 和setter 以及PrePend getter 和setter 中设置了断点,但代码永远不会在那里中断。
这个简单的例子我做错了什么?我不应该使用propdp 代码 sn-p 来执行此操作吗?我不太了解依赖属性。
【问题讨论】:
-
触发 PropertyChanged 事件?
-
我不确定覆盖您的
Text值是否安全。Text中的TextBox也是一个依赖属性。在不更改属性的情况下重新实现它听起来不是一个好主意。 -
我应该把 PropertyChanged 事件放在哪里?在文本设置器中?我对 base.Text setter 的调用不会触发该事件吗?还是 PrePend 设置器?在这种情况下,对 SetValue 的调用不会触发该事件吗?除此之外,如果需要,propdp sn-p 不会包含对 PropertyChanged 的调用吗?
标签: c# wpf dependency-properties