【问题标题】:Problem binding data to controls in dynamically created wpf TabItem问题将数据绑定到动态创建的 wpf TabItem 中的控件
【发布时间】:2011-05-10 06:27:36
【问题描述】:

我在将数据放入 wpf TabItem 上的控件时遇到问题。 我在 xaml 中定义了几个 DataTemplates。这是其中之一:

<Window.Resources>
...
<DataTemplate x:Key="memoTab">
<TextBox Name="memoTextBox" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" AcceptsReturn="True" />
</DataTemplate>
...
</Window.Resources>

然后我在后面的代码中创建新选项卡,如下所示:

TabItem tab = new TabItem();
tab.Header = "Memo";
tab.ContentTemplate = (DataTemplate)FindResource("memoTab");
tab.ApplyTemplate();
System.Windows.Controls.TextBox tb = (System.Windows.Controls.TextBox)tab.Template.FindName("memoTextBox", tab);
if (tb != null) tb.DataContext = memo; //string memo is created earlier as linq query
tabControl.Items.Add(tab); //tabControl is xaml defined

问题在于 tb 始终为空,因此文本框中不会出现任何数据(文本框本身会显示在选项卡中并且可以正常工作)

我不使用 xaml 在 tabControl 中创建选项卡(除了第一个,它不使用 DataTemplate 并且很好),因为它们是由用户在运行时添加和删除的。

有什么想法吗?

【问题讨论】:

    标签: wpf tabitem datatemplate


    【解决方案1】:

    您可能需要获取TabItemContentPresenter。您可以为此参考MSDN

    // Getting the ContentPresenter of tab
    ContentPresenter myContentPresenter = FindVisualChild<ContentPresenter>(tab);
    
    // Finding textBox from the DataTemplate that is set on that ContentPresenter
    DataTemplate myDataTemplate = myContentPresenter.ContentTemplate;
    TextBox myTextBox = (TextBox)myDataTemplate.FindName("memoTextbox", myContentPresenter);
    

    方法 FindVisualChild...

    private childItem FindVisualChild<childItem>(DependencyObject obj)
        where childItem : DependencyObject
    {
        for (int i = 0; i < VisualTreeHelper.GetChildrenCount(obj); i++)
        {
            DependencyObject child = VisualTreeHelper.GetChild(obj, i);
            if (child != null && child is childItem)
                return (childItem)child;
            else
            {
                childItem childOfChild = FindVisualChild<childItem>(child);
                if (childOfChild != null)
                    return childOfChild;
            }
        }
        return null;
    }
    

    【讨论】:

    • 仅更改为 ContentTemplate.FindName 不起作用 - 它给出异常:此操作仅对应用此模板的元素有效。
    • @vdmpal 已编辑答案,查看完整示例的链接,我用您的类型替换了变量。
    • 嗯...当我尝试这个时,ContentPresenter 的 ContentTemplate 始终为空。我什至尝试通过添加 Loaded 事件并在那里运行此代码来推迟它,但没有区别。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多