在我的应用程序中,我有一个带有自定义DataTemplate的ListBox。XAML如下:
<ListBox Name="lstTasks">
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal" VerticalAlignment="Top">
<CheckBox Name="chkIsChecked" VerticalAlignment="Top" IsChecked="{Binding Path=IsChecked, Mode=TwoWay}"/>
<RichTextBox Name="rtbTask" HorizontalAlignment="Left" Height="50" VerticalAlignment="Top" Width="450"
BorderBrush="{DynamicResource {x:Static SystemColors.ActiveCaptionTextBrushKey}}" Margin="0,0,0,10"/>
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
我使用一个名为CheckBoxItem的自定义类作为ListBoxItems。如果我想将一个项目添加到ListBox中,我将使用以下代码作为示例:
lstTasks.Items.Add(new CheckBoxItem("", false));
如果要从ListBox检索此项目,请使用以下代码:
CheckBoxItem CheckBoxItem = (CheckBoxItem)lstTasks.Items[0];
我对数据绑定没有任何问题;它工作正常。我的问题是在DataTemplate中检索一个子级。在应用程序中,用户可以在每个CheckBoxItem中编辑RichTextBox的内容。我希望能够将RichTextBox的内容保存到外部文件。我已经创建了用于获取RTF文本并将其存储在String中的方法,但是对于任何给定的CheckBoxItem,我似乎都无法访问RichTextBox。
我已经在网上搜索了很长时间,但似乎找不到任何有用的信息。使用VisualTree不起作用,因为CheckBoxItems不是DependencyObjects,并且不能强制转换为它们。结果,我非常困惑,非常感谢您对此问题的任何见解。
我的一个想法是跟踪某种类型的集合中的所有RichTextBoxes。我会处理他们的Loaded事件,然后将它们添加到那里的集合中,但是我真的不愿意这样做,因为这似乎是不必要的内存使用。
在此先感谢您的帮助!
没有简单的方法可以做到这一点。但是知道您已经了解了很多VisualTree
东西之后,才可能在下面的示例中看到大多数代码。可能您错过的是第一行,它向您展示了如何从中获得ListBoxItem
收益CheckBoxItem
。有ListBoxItem
手,意味着你有一个DependencyObject
开始使用VisualTree
的东西的技术来寻找RichTextBox
:
var myListBoxItem = (lstTasks.ItemContainerGenerator.ContainerFromItem(lstTasks.Items[0]));
// Getting the ContentPresenter of myListBoxItem
ContentPresenter myContentPresenter = FindVisualChild<ContentPresenter>(myListBoxItem);
// Finding richtextbox from the DataTemplate that is set on that ContentPresenter
DataTemplate myDataTemplate = myContentPresenter.ContentTemplate;
RichTextBox myTextBlock = (RichTextBox)myDataTemplate.FindName("rtbTask", myContentPresenter);
并执行FindVisualChild
如MSDN所示:
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;
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句