我有自定义控件:
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 文本”。
最佳答案
我想你需要了解Dependency Property Value Precedence .
当您使用模板时,依赖属性的值优先级是不同的。
关于.net - 在 DataTemplate 中设置控件属性无法按预期工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9464701/