0

我有一个组合框和一个标签:

<!-- Does not select appropriate value after moving back to current item in collection -->
        <ComboBox
            ItemsSource="{Binding Path=Items}"
            SelectedValue="{Binding Path=SelectedItem, Mode=TwoWay}"
            DisplayMemberPath="ItemName" 
            Margin="8,2,8,16" />

<!-- Displays correctly after moving back to current item in collection -->
        <Label 
        Content="{Binding Path=SelectedItem.ItemName}"/>

我可以在组合框中设置一个项目,但是当我在可观察集合中来回移动到当前项目时,组合框没有像我预期的那样设置 SelectedValue(它保持为空) - 标签的内容设置正确 -并且它绑定到同一件事上。

我究竟做错了什么?

非常感谢任何帮助。

4

1 回答 1

0

尝试使用ICollectionView我在此处描述的(答案)。CollectionView 负责您的组合框,您可以读取和设置当前项目。只需将事件处理程序附加到CurrentChangedICollectionView 中的事件。

XAML:

<ComboBox
      ItemsSource="{Binding Path=Items}"
      DisplayMemberPath="ItemName" 
      IsSynchronizedWithCurrentItem="True" 
      Margin="8,2,8,16" />

<Label Content="{Binding Path=CurrentItem.ItemName}"/>

视图模型:

public class ViewModel :INotifyPropertyChanged
{
    private ObservableCollection<Item> _items= new ObservableCollection<Item>();
    private Item _currentItem;

    public ObservableCollection<Item> Items
    {
        get { return _items; }
        set { _items= value; OnPropertyChanged("Items");}
    }

    public Item CurrentItem
    {
        get { return _currentItem; }
        set { _currentItem = value; OnPropertyChanged("CurrentItem");}
    }

    public ICollectionView ItemsView { get; private set; }

    public ViewModel()
    {
        Items.Add(new Item{Id = Guid.NewGuid(), Name = "Item 1"});
        Items.Add(new Item{Id = Guid.NewGuid(), Name = "Item 2"});
        Items.Add(new Item{Id = Guid.NewGuid(), Name = "Item 3"});

        ItemsView = CollectionViewSource.GetDefaultView(Items);
        ItemsView .CurrentChanged += OnItemsChanged;
        ItemsView .MoveCurrentToFirst();
    }

    private void OnItemsChanged(object sender, EventArgs e)
    {
        var selectedItem = ItemsView .CurrentItem as Item;
        if (selectedItem == null) return;

        CurrentItem= selectedItem ;
    }

    public event PropertyChangedEventHandler PropertyChanged;

    protected virtual void OnPropertyChanged(string propertyName)
    {
        PropertyChangedEventHandler handler = PropertyChanged;
        if (handler != null) handler(this, new PropertyChangedEventArgs(propertyName));
    }
}

public class Item
{
    public Guid Id { get; set; }

    public string Name { get; set; }
}
于 2012-10-31T13:28:08.297 回答