1

I've done this really simple example, is a Window with a TreeView and a Button. When you click the button you should see the selected item, but is not working, the CurrentItem property does not get updated when you change the selection:

C#:

using System.Collections.ObjectModel;
using System.Windows;
using System.Windows.Data;

namespace TreeViewSort
{
public partial class Window1
{
    private ObservableCollection<string> _items;
    public ListCollectionView SortedItems { get; private set; }

    public Window1()
    {
        InitializeComponent();
    }

    private void Window_Loaded(object sender, RoutedEventArgs e)
    {
        _items =new ObservableCollection<string>();
        _items.Add("ZZ");
        _items.Add("AA");
        _items.Add("CA");
        _items.Add("DA");
        _items.Add("EA");

        this.SortedItems = new ListCollectionView(_items);
        this.DataContext = this;
    }

    private void Button_Click(object sender, RoutedEventArgs e)
    {
        MessageBox.Show(this.SortedItems.CurrentItem.ToString());
    }
}
}

XAML:

<Window x:Class="TreeViewSort.Window1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="Window1" Height="300" Width="300" Loaded="Window_Loaded">
    <DockPanel>
        <TreeView DockPanel.Dock="Top" Name="treeView1" ItemsSource="{Binding SortedItems, Mode=TwoWay}" MinHeight="200" />
        <Button DockPanel.Dock="Bottom" Click="Button_Click">
            Test
        </Button>
    </DockPanel>
</Window>

The MSDN documentation says

If the target is an ItemsControl, the current item is synchronized with the selected item

Any idea on why is this not working?

Thanks in advance.

4

3 回答 3

1

即使文档说这将适用于任何 ItemControl 我读过(和看到)的是它只适用于选择器......

于 2011-08-25T11:34:48.887 回答
0

我不得不这样做,但它并不漂亮。我有一个混合树视图/数据网格。为了能够移动到下一个/上一个项目或上下移动项目,我必须执行以下操作。

  1. 将 IsSelected 属性添加到我的模型(hack - 我知道)
  2. 每个模型都有一个排序顺序属性
  3. 在树中选择一个项目时 - 使用 linq 查询查找任何其他已选择的项目并将其标记为未选择
  4. 将刚刚选择的项目标记为 IsSelected
  5. 然后使用自定义逻辑(自定义我的意思是 150 多行代码)来确定下一个项目应该在哪里。但是,此逻辑考虑了在树中折叠的项目和两个级别(父/子)。

IIRC 我必须这样做的原因是我需要的值在可视树上,但我正在使用逻辑树。

于 2011-08-25T17:15:44.787 回答
0

我不确定 ListCollectionView 中的 CurrentItem,请尝试在下面执行此操作:在 Window1 类中创建一个属性 -> public string SelectedItem { get; 放; 在 XAML 中,将树视图控件 SelectedItem 属性与您的 SelectedItem 属性绑定。

应该管用。

关于 SelectedItem -> http://msdn.microsoft.com/en-us/library/system.windows.controls.treeview.selecteditem.aspx

问候帕维尔扬科夫斯基

于 2011-08-25T09:54:59.743 回答