Tho*_*att 49 .net c# wpf treeview itemscontrol
如何以编程方式选择WPF中的项目TreeView?该ItemsControl模型似乎阻止了它.
小智 39
对于那些仍在寻找解决这个问题的人来说,下面就是这个问题.我在DaWanderer 的代码项目文章"WPF TreeView Selection" http://www.codeproject.com/KB/WPF/TreeView_SelectionWPF.aspx的评论中找到了这个.它由Kenrae于2008年11月25日发布.这对我来说非常有用.谢谢Kenrae!
让自己的数据对象具有IsSelected属性(我也建议使用IsExpanded属性),而不是走树.使用TreeView上的ItemContainerStyle属性为TreeViewItems定义样式,该属性将TreeViewItem中的这些属性绑定到数据对象.像这样的东西:
<Style x:Key="LibraryTreeViewItemStyle"
TargetType="{x:Type TreeViewItem}">
<Setter Property="IsExpanded"
Value="{Binding IsExpanded, Mode=TwoWay}" />
<Setter Property="IsSelected"
Value="{Binding IsSelected, Mode=TwoWay}" />
<Setter Property="FontWeight"
Value="Normal" />
<Style.Triggers>
<Trigger Property="IsSelected"
Value="True">
<Setter Property="FontWeight"
Value="Bold" />
</Trigger>
</Style.Triggers>
</Style>
<TreeView ItemsSource="{Binding Path=YourCollection}"
ItemContainerStyle="{StaticResource LibraryTreeViewItemStyle}"
ItemTemplate={StaticResource YourHierarchicalDataTemplate}/>
Run Code Online (Sandbox Code Playgroud)
Ste*_*ins 27
出于某些奇怪的原因,这是一个真正的痛苦,您必须使用ContainerFromItem来获取容器,然后调用select方法.
// selectedItemObject is not a TreeViewItem, but an item from the collection that
// populated the TreeView.
var tvi = treeView.ItemContainerGenerator.ContainerFromItem(selectedItemObject)
as TreeViewItem;
if (tvi != null)
{
tvi.IsSelected = true;
}
Run Code Online (Sandbox Code Playgroud)
曾经有一篇关于如何在这里做的博客文章,但现在链接已经死了.
Ken*_*art 23
您需要获取TreeViewItem然后设置IsSelected为true.
我已成功使用此代码:
public static TreeViewItem FindTviFromObjectRecursive(ItemsControl ic, object o) {
//Search for the object model in first level children (recursively)
TreeViewItem tvi = ic.ItemContainerGenerator.ContainerFromItem(o) as TreeViewItem;
if (tvi != null) return tvi;
//Loop through user object models
foreach (object i in ic.Items) {
//Get the TreeViewItem associated with the iterated object model
TreeViewItem tvi2 = ic.ItemContainerGenerator.ContainerFromItem(i) as TreeViewItem;
tvi = FindTviFromObjectRecursive(tvi2, o);
if (tvi != null) return tvi;
}
return null;
}
Run Code Online (Sandbox Code Playgroud)
用法:
var tvi = FindTviFromObjectRecursive(TheTreeView, TheModel);
if (tvi != null) tvi.IsSelected = true;
Run Code Online (Sandbox Code Playgroud)
这并不像看起来那么简单,Steven提供的链接在2008年发布了一个解决方案,该解决方案可能仍然有效,但不会处理Virtualized TreeViews.此外,该条的评论中还提到了许多其他问题.没有违法行为,但我也遇到了同样的问题,无法找到完美的解决方案.以下是一些帮助我很多的文章/帖子的链接 -
如何在TreeView中展开项目?- 第三部分:http: //bea.stollnitz.com/blog/?p = 59
以编程方式在TreeView中选择项目:http: //blog.quantumbitdesigns.com/2008/07/22/programmatically-selecting-an-item-in-a-treeview/#respond
TreeView,TreeViewItem和IsSelected:http://social.msdn.microsoft.com/Forums/en-US/wpf/thread/7e368b93-f509-4cd6-88e7-561e8d3246ae/
| 归档时间: |
|
| 查看次数: |
64400 次 |
| 最近记录: |