我有自定义控件:
public class TestTextBox : TextBox
{
public TestTextBox()
{
Text = "ctor text";
}
}
使用此控件的xaml:
<StackPanel Orientation="Vertical">
<!-- 1. Use TestTextBox directly -->
<controls:TestTextBox Text="xaml text"/>
<!-- 2. Use TestTextBox in DataTemplate -->
<ItemsControl>
<ItemsControl.ItemTemplate>
<DataTemplate>
<controls:TestTextBox Text="xaml text"/>
</DataTemplate>
</ItemsControl.ItemTemplate>
<System:String>111</System:String>
</ItemsControl>
<StackPanel>
结果是TestTextBox.Text在这些情况下是不同的 - 第一种情况下为“xaml text”,第二种情况下为“ctor text”。
有人可以解释为什么它会这样运作吗?在这两种情况下,我都希望TestTextBox.Text是“xaml text”。
答案 0 :(得分:1)
我认为您需要了解Dependency Property Value Precedence。
使用模板时,依赖项属性的值优先级不同。
答案 1 :(得分:1)
看来你做的不正确。它实际上没有呈现文本框,因为您没有给出项目源。或者你能做的就是
<ItemsControl.Items>
<TestTextBoxFet:TestTextBox Text="xaml text"/>
</ItemsControl.Items>
答案 2 :(得分:0)
我同意gaurawerma。
构造函数中设置的值的优先级高于数据模板中设置的优先级。 因此,在两种情况下,您都会看到结果不同。
http://social.msdn.microsoft.com/Forums/en/wpf/thread/a4e7ed36-9a8a-48ce-a5d5-00a49376669b