将数据绑定到动态创建的 wpf TabItem 中的控件时出现问题
我在将数据放入 wpf TabItem 的控件中时遇到问题。 我在xaml中定义了几个DataTemplate。这是其中之一:
<代码> <窗口.资源>
...
...
然后,我在后面的代码中创建新选项卡,如下所示:
TabItem tab = new TabItem();
tab.Header = "备忘录";
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 = 备忘录; //字符串备忘录是之前作为 linq 查询创建的
tabControl.Items.Add(tab); //tabControl是xaml定义的
问题是tb总是为null,因此文本框中没有数据出现(文本框本身显示在选项卡中并且它是功能性的)
我不使用xaml来创建tabControl 中的选项卡(第一个选项卡除外,它没有使用 DataTemplate 并且很好),因为它们是由用户在运行时添加和删除的。
有什么想法吗?
I am having problem putting data into controls on wpf TabItem.
I have defined several DataTemplates in xaml. Here is one of them:
<Window.Resources>
...
<DataTemplate x:Key="memoTab">
<TextBox Name="memoTextBox" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" AcceptsReturn="True" />
</DataTemplate>
...
</Window.Resources>
I then create new tab in code behind as follows:
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
The problem is that tb is always null, and therefore no data appears in the text box (the text box itself shows up in the tab and it is functional)
I do not use xaml to create tabs in tabControl (except the first one, which is not using DataTemplate and is fine) because they are meant to be added and removed by the user at run time.
Any ideas?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可能需要获取
TabItem
的ContentPresenter
。您可以为此参考 MSDN。FindVisualChild 方法...
You may need to get the
ContentPresenter
of theTabItem
. You can reference the MSDN for this.The method FindVisualChild...