TemplateBinding不适用于文本框文本 [英] TemplateBinding not working for textbox text
问题描述
我有一个名为 EnhancedTextBox
的自定义控件,它是一个具有 TextBox
和按钮
。对于消费者来说,我希望它看起来像一个文本框,所以我做了以下操作:
I have a custom control called EnhancedTextBox
which is a UserControl that has a TextBox
and a Button
. To the consumer I want it to mostly look like a TextBox, so I did the following:
<UserControl.Template>
<ControlTemplate TargetType="textBoxes:EnhancedTextBox">
...
<TextBox Text="{TemplateBinding Text}"...
并且在EnhancedTextBox中,我有
And in EnhancedTextBox I have
public static readonly DependencyProperty TextProperty =
DependencyProperty.Register("Text", typeof (String), typeof (EnhancedTextBox));
public String Text
{
get { return (String) GetValue(TextProperty); }
set { SetValue(TextProperty, value); }
}
但是,当我按以下方式使用它时:
Yet, when I use it as the following:
<EnhancedTextBox Text="{Binding MyText, Mode=TwoWay, NotifyOnSourceUpdated=True, UpdateSourceTrigger=PropertyChanged}}" />
然后, MyText
从未更新,因为以及检查 EnhancedTextBox.Text
时,它为null。我想念什么?我一直盯着这个看了一眼,不知道出什么问题了。我什至认为这可能是我使用相同名称的事实,因此创建一个名为 Text1
的属性,该属性不起作用....
Then, MyText
is never updated, as well as I inspect EnhancedTextBox.Text
and it is null. What am I missing? I have been staring at this for a bit and can't figure out what is wrong. I even thought it might be the fact that I was using the same name, so create a property called Text1
which did not work....
还要注意,如果我使用常规的 TextBox
,那么这一切都可行。因此,我相当确定问题出在 EnhancedTextBox
本身
Also of note, if I use a regular TextBox
, then this all works. So, I am fairly certain the problem is with the EnhancedTextBox
itself
推荐答案
在阅读有关模板绑定的MSDN 后,我就知道了。具体来说,
I figured it out after reading this MSDN about TemplateBinding. Specifically,
TemplateBinding是针对模板方案的Binding的优化形式,类似于使用 {Binding RelativeSource = {RelativeSource TemplatedParent}} 。
因此,我决定明确地执行此操作...这将允许我进行设置 UpdateSourceTrigger
(仍然不确定为什么它不默认为 PropertyChanged
)
So, I decided to do this explicitly...which would allow me to set the UpdateSourceTrigger
(still not sure why it doesn't default to PropertyChanged
)
<TextBox Text="{Binding RelativeSource={RelativeSource TemplatedParent}, Path=Text, UpdateSourceTrigger=PropertyChanged}"....
现在,它正在工作。 TemplateBinding
甚至都没有公开这些属性....再次不确定为什么
And, now it is working. TemplateBinding
does not even expose these properties....again, not sure why
这篇关于TemplateBinding不适用于文本框文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!