刷新ListCollectionView会将ComboBox中选定项的值设置为null。

5
我有一个视图,其中包含一个ListBox和两个ComboBox。当我在ListBox中选择一个项目时,基于所选项目的属性值,ComboBox的内容/值会刷新。在我的场景中,ListBox保存客户列表,第一个ComboBox保存国家列表。所选项目是客户的出生国家。第二个ComboBox保存城市列表。所选城市是客户的出生城市。
第二个ComboBox的ItemsSource属性绑定到基于ObservableCollection的ListViewCollection,该集合包含所有城市,并使用过滤器进行筛选。当国家ListBox中的选择更改时,我刷新过滤器以仅显示属于所选国家的城市。
假设客户A来自新西兰奥克兰,客户B来自加拿大多伦多。当我选择A时,一切正常。第二个ComboBox仅填充了新西兰城市,并选择了奥克兰。现在我选择B,所选国家现在是加拿大,城市列表仅包含加拿大城市,多伦多被选中。如果现在我回到A,新西兰在国家中被选中,城市列表仅包含新西兰城市,但未选中奥克兰。
当我调试此场景时,我注意到当我选择B时,对ListCollectionView.Refresh()的调用将最初选择的客户A的城市值设置为null(在Refresh调用和模型上的城市setter处放置断点,参见下面的代码)。
我猜测(虽然不确定),这是因为我在city ComboBox的SelectedItem上有一个TwoWay绑定,当过滤器更新到加拿大城市时,奥克兰消失并将此信息发送回属性,然后将其更新为null。从某种意义上讲,这是有道理的。
我的问题是:如何避免发生这种情况?如何防止在仅“刷新”ItemsSource时更新模型上的属性?
以下是我的代码(它有点长,尽管我试图使它尽可能小以重现问题):
public class Country
{
    public string Name { get; set; }
    public IEnumerable<City> Cities { get; set; }
}

public class City
{
    public string Name { get; set; }
    public Country Country { get; set; }
}

public class ClientModel : NotifyPropertyChanged
{
    #region Fields
    private string name;
    private Country country;
    private City city;
    #endregion

    #region Properties
    public string Name
    {
        get
        {
            return this.name;
        }

        set
        {
            this.name = value;
            this.OnPropertyChange("Name");
        }
    }

    public Country Country
    {
        get
        {
            return this.country;
        }

        set
        {
            this.country = value;
            this.OnPropertyChange("Country");
        }
    }

    public City City
    {
        get
        {
            return this.city;
        }

        set
        {
            this.city = value;
            this.OnPropertyChange("City");
        }
    }
    #endregion
}

public class ViewModel : NotifyPropertyChanged
{
    #region Fields
    private ObservableCollection<ClientModel> models;
    private ObservableCollection<Country> countries;
    private ObservableCollection<City> cities;
    private ListCollectionView citiesView;

    private ClientModel selectedClient;
    #endregion

    #region Constructors
    public ViewModel(IEnumerable<ClientModel> models, IEnumerable<Country> countries, IEnumerable<City> cities)
    {
        this.Models = new ObservableCollection<ClientModel>(models);
        this.Countries = new ObservableCollection<Country>(countries);
        this.Cities = new ObservableCollection<City>(cities);
        this.citiesView = (ListCollectionView)CollectionViewSource.GetDefaultView(this.cities);
        this.citiesView.Filter = city => ((City)city).Country.Name == (this.SelectedClient != null ? this.SelectedClient.Country.Name : string.Empty);

        this.CountryChangedCommand = new DelegateCommand(this.OnCountryChanged);
    }
    #endregion

    #region Properties
    public ObservableCollection<ClientModel> Models
    {
        get
        {
            return this.models;
        }

        set
        {
            this.models = value;
            this.OnPropertyChange("Models");
        }
    }

    public ObservableCollection<Country> Countries
    {
        get
        {
            return this.countries;
        }

        set
        {
            this.countries = value;
            this.OnPropertyChange("Countries");
        }
    }

    public ObservableCollection<City> Cities
    {
        get
        {
            return this.cities;
        }

        set
        {
            this.cities = value;
            this.OnPropertyChange("Cities");
        }
    }

    public ListCollectionView CitiesView
    {
        get
        {
            return this.citiesView;
        }
    }

    public ClientModel SelectedClient
    {
        get
        {
            return this.selectedClient;
        }

        set
        {
            this.selectedClient = value;
            this.OnPropertyChange("SelectedClient");
        }
    }

    public ICommand CountryChangedCommand { get; private set; }

    #endregion

    #region Methods
    private void OnCountryChanged(object obj)
    {
        this.CitiesView.Refresh();
    }
    #endregion
}

现在这里是XAML代码:

    <Grid Grid.Column="0" DataContext="{Binding SelectedClient}">
        <Grid.ColumnDefinitions>
            <ColumnDefinition/>
            <ColumnDefinition/>
        </Grid.ColumnDefinitions>
        <Grid.RowDefinitions>
            <RowDefinition Height="25"/>
            <RowDefinition Height="25"/>
        </Grid.RowDefinitions>

        <TextBlock Grid.Column="0" Grid.Row="0" Text="Country"/>
        <local:ComboBox Grid.Column="1" Grid.Row="0" SelectedItem="{Binding Country}"
                        Command="{Binding DataContext.CountryChangedCommand, RelativeSource={RelativeSource AncestorType={x:Type local:MainWindow}}}"
                        ItemsSource="{Binding DataContext.Countries, RelativeSource={RelativeSource AncestorType={x:Type local:MainWindow}}}">
            <local:ComboBox.ItemTemplate>
                <DataTemplate>
                    <TextBlock Text="{Binding Name}"/>
                </DataTemplate>
            </local:ComboBox.ItemTemplate>
        </local:ComboBox>

        <TextBlock Grid.Column="0" Grid.Row="1" Text="City"/>
        <ComboBox Grid.Column="1" Grid.Row="1" SelectedItem="{Binding City}"
                  ItemsSource="{Binding DataContext.CitiesView, RelativeSource={RelativeSource AncestorType={x:Type local:MainWindow}}}">
            <ComboBox.ItemTemplate>
                <DataTemplate>
                    <TextBlock Text="{Binding Name}"/>
                </DataTemplate>
            </ComboBox.ItemTemplate>
        </ComboBox>
    </Grid>

    <ListBox Grid.Column="1" ItemsSource="{Binding Models}" SelectedItem="{Binding SelectedClient}">
        <ListBox.ItemTemplate>
            <DataTemplate>
                <TextBlock Text="{Binding Name}"/>
            </DataTemplate>
        </ListBox.ItemTemplate>
    </ListBox>
</Grid>

如果有帮助的话,这是我自定义的ComboBox代码,用于处理国家选择更改的通知。
public class ComboBox : System.Windows.Controls.ComboBox, ICommandSource
{
    #region Fields
    public static readonly DependencyProperty CommandProperty = DependencyProperty.Register(
        "Command",
        typeof(ICommand),
        typeof(ComboBox));

    public static readonly DependencyProperty CommandParameterProperty = DependencyProperty.Register(
        "CommandParameter",
        typeof(object),
        typeof(ComboBox));

    public static readonly DependencyProperty CommandTargetProperty = DependencyProperty.Register(
        "CommandTarget",
        typeof(IInputElement),
        typeof(ComboBox));
    #endregion

    #region Properties
    public ICommand Command
    {
        get { return (ICommand)this.GetValue(CommandProperty); }
        set { this.SetValue(CommandProperty, value); }
    }

    public object CommandParameter
    {
        get { return this.GetValue(CommandParameterProperty); }
        set { this.SetValue(CommandParameterProperty, value); }
    }

    public IInputElement CommandTarget
    {
        get { return (IInputElement)this.GetValue(CommandTargetProperty); }
        set { this.SetValue(CommandTargetProperty, value); }
    }
    #endregion

    #region Methods

    protected override void OnSelectionChanged(System.Windows.Controls.SelectionChangedEventArgs e)
    {
        base.OnSelectionChanged(e);

        var command = this.Command;
        var parameter = this.CommandParameter;
        var target = this.CommandTarget;

        var routedCommand = command as RoutedCommand;
        if (routedCommand != null && routedCommand.CanExecute(parameter, target))
        {
            routedCommand.Execute(parameter, target);
        }
        else if (command != null && command.CanExecute(parameter))
        {
            command.Execute(parameter);
        }
    }
    #endregion
}

这里给出一个简单的例子,我在Window的构造函数中创建和填充了视图模型,如下所示:

public MainWindow()
{
    InitializeComponent();

    Country canada = new Country() { Name = "Canada" };
    Country germany = new Country() { Name = "Germany" };
    Country vietnam = new Country() { Name = "Vietnam" };
    Country newZealand = new Country() { Name = "New Zealand" };

    List<City> canadianCities = new List<City>
    {
        new City { Country = canada, Name = "Montréal" },
        new City { Country = canada, Name = "Toronto" },
        new City { Country = canada, Name = "Vancouver" }
    };
    canada.Cities = canadianCities;

    List<City> germanCities = new List<City>
    {
        new City { Country = germany, Name = "Frankfurt" },
        new City { Country = germany, Name = "Hamburg" },
        new City { Country = germany, Name = "Düsseldorf" }
    };
    germany.Cities = germanCities;

    List<City> vietnameseCities = new List<City>
    {
        new City { Country = vietnam, Name = "Ho Chi Minh City" },
        new City { Country = vietnam, Name = "Da Nang" },
        new City { Country = vietnam, Name = "Hue" }
    };
    vietnam.Cities = vietnameseCities;

    List<City> newZealandCities = new List<City>
    {
        new City { Country = newZealand, Name = "Auckland" },
        new City { Country = newZealand, Name = "Christchurch" },
        new City { Country = newZealand, Name = "Invercargill" }
    };
    newZealand.Cities = newZealandCities;

    ObservableCollection<ClientModel> models = new ObservableCollection<ClientModel>
    {
        new ClientModel { Name = "Bob", Country = newZealand, City = newZealandCities[0] },
        new ClientModel { Name = "John", Country = canada, City = canadianCities[1] }
    };

    List<Country> countries = new List<Country>
    {
        canada, newZealand, vietnam, germany
    };

    List<City> cities = new List<City>();
    cities.AddRange(canadianCities);
    cities.AddRange(germanCities);
    cities.AddRange(vietnameseCities);
    cities.AddRange(newZealandCities);

    ViewModel vm = new ViewModel(models, countries, cities);

    this.DataContext = vm;
}

通过简单地复制/粘贴上述所有代码应该可以重现问题。 我正在使用.NET 4.0。

最后,我阅读了这篇文章(以及其他一些文章),并尝试将给定的建议适应/应用到我的情况,但没有任何成功的经验。 我想我做错了事情:

我还阅读了这个问题,但如果我的 ListBox 变得很大,我可能最终不得不明确跟踪数百个项,如果可能的话,我不想这样做。

1个回答

2
您有一个有点冗余的模型。您有一个国家列表,每个国家都有城市列表。然后,您组成了整个城市列表,并在选择更改时更新它。如果您更改城市ComboBox的数据源,您将获得所需的行为:
    <ComboBox Grid.Column="1" Grid.Row="1" SelectedItem="{Binding City}"
              ItemsSource="{Binding Country.Cities}">
        <ComboBox.ItemTemplate>
            <DataTemplate>
                <TextBlock Text="{Binding Name}"/>
            </DataTemplate>
        </ComboBox.ItemTemplate>
    </ComboBox>

你对于为什么城市被设置为 "null" 有一个正确的猜测。
但是,如果你想保留上面描述的模型,你应该改变方法调用的顺序。为了做到这一点,你应该使用 Application.Current.Dispatcher 属性(而且你不需要改变上面提到的 ComboBox)。
private void OnCountryChanged()
{
    var uiDispatcher = System.Windows.Application.Current.Dispatcher;
    uiDispatcher.BeginInvoke(new Action(this.CitiesView.Refresh));
}

我尝试了两种解决方案,它们都可以工作。我会选择第一个方案,因为代码更简洁易懂且易于维护。但是,我真的很想知道为什么使用UI调度程序有助于解决问题??虽然我没有调试代码来了解发生了什么,但据我所知,一切都已经在UI线程上运行,我无法想象为什么使用UI调度程序能以某种方式帮助... - Guillaume
UI调度程序的BeginInvoke()方法将安排在UI线程上调用该方法,因此当UI线程空闲以执行某些操作时,它将执行您指定的操作。因此,在选择SelectedClient之后,将首先选择SelectedClient,然后将应用于CitiesView的过滤器。 - stukselbax

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接