WPF ObservableCollection CollectionView.CurrentChanged没有触发

时间:2010-02-11 11:03:19

标签: c# wpf .net-3.5 observablecollection icollectionview

我的ICollectionView之一出了问题。 ICollectionView的{​​{1}}事件未触发。

请参阅下面的代码。

XAML:

CurrentChanged

AND C#(ViewModel)

            <!-- Publication -->
            <TextBlock Name="tbkPublication" Text="{x:Static abConst:Print.tbkPublicationText}" Grid.Row="0" Grid.Column="0" Margin="3" ></TextBlock>
            <ComboBox Grid.Column="1" Grid.Row="0"  Margin="3" 
                      Name="cmbPublication" BorderThickness="1" 
                      ItemsSource="{Binding Path=EnterpriseList}" DisplayMemberPath="Name" 
                      SelectedValuePath="Value" SelectedIndex="0" 
                      IsSynchronizedWithCurrentItem="True" />

            <!-- Distribution Area Region -->
            <TextBlock Name="tbkDistributionArea" Text="{x:Static abConst:Print.tbkDistributionAreaText}" Grid.Row="1" Grid.Column="0" Margin="3" ></TextBlock>
            <ComboBox Grid.Column="1" Grid.Row="1"  Margin="3" 
                      Name="cmbDistributionArea" BorderThickness="1" 
                      ItemsSource="{Binding Path=ZonesList}" 
                      DisplayMemberPath="Name" 
                      SelectedValuePath="Value" SelectedIndex="0" 
                      IsSynchronizedWithCurrentItem="True" />

请帮忙。提前谢谢。

1 个答案:

答案 0 :(得分:4)

您需要将组合框数据绑定到集合视图而不是底层集合。以下是一份工作样本:

XAML:

<Window x:Class="CurrentChangedTest.Window1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Height="300" Width="300">
    <StackPanel>

        <ComboBox 
              ItemsSource="{Binding Path=ZoneCollView}" 
              DisplayMemberPath="Value" 
              SelectedIndex="0" 
              IsSynchronizedWithCurrentItem="True" />

        <TextBlock Text="{Binding Path=ZoneCollView.CurrentItem}" />

    </StackPanel>
</Window>

代码背后:

using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Windows;
using System.Windows.Data;

namespace CurrentChangedTest
{
    public partial class Window1 : Window
    {
        public Window1()
        {
            InitializeComponent();

            _zoneList.Add(new KeyValuePair<int, string>(0, "zone 0"));
            _zoneList.Add(new KeyValuePair<int, string>(1, "zone 1"));
            _zoneList.Add(new KeyValuePair<int, string>(2, "zone 2"));

            ZoneCollView = new CollectionView(_zoneList);
            ZoneCollView.CurrentChanged +=
                delegate { Debug.WriteLine(ZoneCollView.CurrentItem); };

            DataContext = this;
        }

        public ICollectionView ZoneCollView { get; set; }

        private List<KeyValuePair<int, string>> _zoneList = new List<KeyValuePair<int, string>>();
    }
}