SelectedItemChanged事件

SelectedItemChanged事件

我目前有一个WPF树视图,其结构为:

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

我目前有一个SelectedItemChanged事件处理程序,像这样连接到该树视图
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
     }
}

所以我的问题是,如何使树状视图的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/

10-13 03:14