.net - 在 DataTemplate 中设置控件属性无法按预期工作

标签 .net wpf datatemplate

我有自定义控件:

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/

相关文章:

c# - WCF——解决方案架构

c# - 在文本文件的顶部添加一行

c# - 如何防止 LocalDB 在空闲时间后分离 MDF 文件?

c# - WPF 本地化扩展 : Translate window at run-time

MVVM + Datacontext + DataTemplate + Blend = 问题

c# - 使用 OpenFileDialog/C#/.Net 保留最后选择的路径

c# - 在单元格值中绑定(bind) WPF DataGrid 列标题文本

WPF 文本框拉伸(stretch)

wpf - 如何将 ObservableCollection 绑定(bind)到 DataTemplate 中的文本框?

c# - WPF - 隐藏 ItemsControl -> UniformGrid 中的项目基于数据绑定(bind)不占用 UI 空间