I have a view with ListBoxand two ComboBoxes. When I select an element in ListBox, the contents / value of ComboBoxes is updated depending on the property value of the selected element. In my scenario it ListBoxcontains a list of clients, the first one ComboBoxcontains a list of countries. The item selected is the country of origin of the customer. The second ComboBoxcontains a list of cities. The selected city is the city of origin of the customer.
The property of the ItemsSourcesecond is ComboBoxtied to ListViewCollectionbased on ObservableCollection all cities using the filter. When the selection in a country ListBoxchanges, I update the filter to display only cities belonging to the selected country.
Suppose client A is in Auckland, New Zealand, and client B is from Toronto, Canada. When I select A, everything works fine. The second ComboBoxis inhabited only by New Zealand cities and Auckland is selected. Now I select B, and the selected country is now Canada, and in the list of cities there are only Canadian cities, Toronto is selected. If now I return to A, then New Zealand will be selected in New Zealand, the list of cities includes only cities from New Zealand, but Auckland is not selected.
When I debug this scenario, I notice that when I select B, the call ListCollectionView.Refresh()sets the city value on client A originally selected for null(place a breakpoint on Refresh and the other one on the city setter in the model, see code below).
I think, although I'm not 100% sure that this is happening because I have a snap TwoWayto SelectedItemcities ComboBox, and when the filter updates the list in Canadian cities, Auckland disappears and this information is sent back to the property, which is then updated to null. Which, in a sense, makes sense.
My question is: how can I avoid this? How can I prevent the updating of the properties of my model when updating 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 , , .