C# 复选框单击“将文本块复制到字符串列表”
在HierarchycalDataTemplate中,我得到了2个C# 复选框单击“将文本块复制到字符串列表”,c#,wpf,treeview,hierarchicaldatatemplate,C#,Wpf,Treeview,Hierarchicaldatatemplate,在HierarchycalDataTemplate中,我得到了2个textblocks,我想从这两个模板中复制文本。在复选框中,单击/选中该复选框将文本更新为列表 函数从一个文本块获取文本 如何从两个文本块中获取文本并将其更新到列表中 private List<string> selectedNames = new List<string>(); private void TreeView_Checked(object sender, RoutedEventArgs e)
textblocks
,我想从这两个模板中复制文本。在复选框中,单击/选中该复选框将文本更新为列表
函数从一个文本块获取文本
如何从两个文本块中获取文本并将其更新到列表中
private List<string> selectedNames = new List<string>();
private void TreeView_Checked(object sender, RoutedEventArgs e)
{
CheckBox chkBox = sender as CheckBox;
StackPanel stackPanel = chkBox.Parent as StackPanel;
TextBlock txtBlock = FindVisualChild<TextBlock>(stackPanel);
bool isChecked = chkBox.IsChecked.HasValue ? chkBox.IsChecked.Value : false;
if (isChecked)
{
selectedNames.Add(txtBlock.Text );
}
}
private List selectedNames=new List();
已选中私有无效树视图(对象发送方、路由目标)
{
复选框chkBox=发送方为复选框;
StackPanel StackPanel=chkBox.Parent作为StackPanel;
TextBlock txtBlock=FindVisualChild(stackPanel);
bool isChecked=chkBox.isChecked.HasValue?chkBox.isChecked.Value:false;
如果(已检查)
{
选择名称。添加(txtBlock.Text);
}
}
复选框获取文本功能:
private static T FindVisualChild<T>(DependencyObject obj) where T : DependencyObject
{
for (int i = 0; i < VisualTreeHelper.GetChildrenCount(obj); i++)
{
DependencyObject child = VisualTreeHelper.GetChild(obj, i);
if (child != null && child is T)
return (T)child;
else
{
T childOfChild = FindVisualChild<T>(child);
if (childOfChild != null)
return childOfChild;
}
}
return null;
}
private static T FindVisualChild(DependencyObject obj),其中T:DependencyObject
{
for(int i=0;i
WPF HierarchycalDataTemplate:
<StackPanel Orientation="Horizontal" >
<CheckBox Name="checkBoxTree" Checked="TreeView_Checked" Unchecked="checkBoxTree_Unchecked"
Margin="0,4,0,0" Style="{DynamicResource CheckBoxStyle1}"/>
<TextBlock Text="{Binding XPath=@Name, Mode=TwoWay}" />
<TextBlock >
<Hyperlink NavigateUri="{Binding XPath=@WebSite}" RequestNavigate="Hyperlink_RequestNavigate">
<TextBlock Text="{Binding XPath=@WebSite}" />
</Hyperlink>
</TextBlock>
</StackPanel>
目前我无法测试此功能,但我认为它应该可以工作: 然后抓住
ContentPresenter
,像这样使用它:
TextBlock secondTextBlock = dataTemplate.
FindName("SecondTextBlock", contentPresenter) as TextBlock;
if (secondTextBlock != null) selectedNames.Add(secondTextBlock.Text );
当我在VisualTree应用新的超链接文本块时,出现空异常错误。哪个对象是
null
?我知道“超链接”对象是空的。在多个节点中,只有超链接的某个节点具有该值。例如:
@Shreidan:我尝试了你的解决方案,但仍然从超链接文本块中获得了空白命运。我不知道下一步该怎么办?
<Hyperlink NavigateUri="{Binding XPath=@WebSite}"
RequestNavigate="Hyperlink_RequestNavigate">
<TextBlock Name="SecondTextBlock" Text="{Binding XPath=@WebSite}" />
</Hyperlink>
TextBlock secondTextBlock = dataTemplate.
FindName("SecondTextBlock", contentPresenter) as TextBlock;
if (secondTextBlock != null) selectedNames.Add(secondTextBlock.Text );