gpt4 book ai didi

c# - 在 SelectedItemChanged 事件中更改 WPF TreeView SelectedItem

转载 作者:行者123 更新时间:2023-12-01 18:46:36 25 4
gpt4 key购买 nike

我目前有一个结构如下的 WPF Treeview:

--> Group 1 (Hierarchical Group)
---> Group 2 (Hierarchical Group)
---> Item 1
---> Item 2
---> Item 3

我目前有一个 SelectedItemChanged 事件处理程序连接到此 TreeView

private void TreeViewControl_SelectedItemChanged(object sender, RoutedPropertyChangedEventArgs<object> e)
{

if (e.NewValue is Item)
{
Item item = e.NewValue as Item;
if (Item != SelectedItem)
{
//keep SelectedItem in sync with Treeview.SelectedItem
SelectedItem = e.NewValue as Item;
}

}
else
{
//if the user tries to select an object that isn't an Item (i.e. a group) reselect the first Item in that group
//This will then cause stack overflow in methods I've tried so far
}
}

所以我的问题是,如何使 TreeView 的 SelectedItem 与我后面代码中的 SelectedItem 属性保持同步,以及如果用户选择了一个组,我如何重新选择一个项目?

编辑:

    <TreeView Grid.Row="1" Grid.RowSpan="2"
ItemContainerStyle="{StaticResource StandardListStyle}"
ItemTemplate="{StaticResource TreeViewItemTemplate}"
BorderThickness="1,0,1,1"
VerticalContentAlignment="Stretch"
HorizontalAlignment="Stretch"
ItemsSource="{Binding Teams}"
SelectedItemChanged="TreeViewControl_SelectedItemChanged"
Loaded="OnTreeViewLoaded"
x:Name="TreeViewControl">

哪里:

Teams = List<HierachicalGroup>;

在哪里:

public class HierachicalGroup
{
public virtual string Name { get; set; }
public virtual HierachicalGroup[] Children { get; set; }
public virtual HierachicalGroup Parent { get; set; }
}

项目是:

public class Item: HierachicalGroup
{
public Domain Domain { get; set; }

public override string Name
{
get
{
return Domain.DomainName;
}
}
}

最佳答案

在 TreeView.SelectedItemChanged 事件中,我们得到 e.NewValue,它是 TreeViewItem 的类型,因此我认为您可以使用以下代码在选择项目组时选择项目。

var item = (e.NewValue as TreeViewItem);
if (item.Items.Count > 0)
{
(item.Items[0] as TreeViewItem).IsSelected = true;
}

关于c# - 在 SelectedItemChanged 事件中更改 WPF TreeView SelectedItem,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24756011/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com