In my application I have items which can contain a Town
. Each Town
consists of a PostalCode
and a Name
, e.g.
<Code>
<Row
Code="1234"
Name="County A - Town A"
/>
</Code>
<Code>
<Row
Code="1234"
Name="County A - Town B"
/>
</Code>
<Code>
<Row
Code="1235"
Name="County B"
/>
</Code>
<Code>
<Row
Code="1236"
Name="County C"
/>
</Code>
The PostalCode
can be repeated for several towns.
In my UI I show the selection as follows:
But this is confusing for the user, as there are multiple similar PostalCode
s.
Is there a way to group the Town
s by each distinct PostalCode
and filter the second ComboBox
with the filtered Name
s?
An important remark is that a Town
is a property of an Item
, which is my ListView
's ItemsSource
.
Edit
I've changed my code as suggested to the following:
XAML
<ComboBox x:Name="PostalCodeComboBox"
ItemsSource="{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type ListView}}, Path=DataContext.DistinctPostalCodeTowns}"
SelectedItem="{Binding Address.Town}" SelectionChanged="PostalCodeComboBox_SelectionChanged" />
<ComboBox x:Name="NameComboBox"
ItemsSource="{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type ListView}}, Path=DataContext.TownsByCode}"
SelectedItem="{Binding Address.Town}" SelectionChanged="NameComboBox_SelectionChanged" />
ViewModel
public MainWindowViewModel()
{
VivendaContext = new DataModels.VivendaContext();
//Call a ToList to load the data into the .Local property.
VivendaContext.Premises.ToList();
Premises = VivendaContext.Premises.Local;
Towns = VivendaContext.Towns.ToList();
//http://stackoverflow.com/a/1300116/1653998
DistinctPostalCodeTowns = VivendaContext.Towns.DistinctBy(t => t.PostalCode).ToList();
TownsByCode = Towns;
}
internal void PostalCodeComboBox_SelectionChanged(ComboBox sender)
{
if(sender.SelectedItem as Town != null)
{
TownsByCode = Towns.Where(t => t.PostalCode == (sender.SelectedItem as Town).PostalCode).ToList();
} else
{
TownsByCode = Towns;
}
}
And this works wonderfully when I select a PostalCode
, it filters the towns with that postalcode. But when I load my data (or select a Town
via its Name
), I only get to see a PostalCode
when it's the first town with that postalcode.
I know this is a side-effect of the DistinctBy
and the fact that not all Town
Entities are available in my DistinctPostalCodeTowns
property.
My first thought was to use the SelectionChanged
event on my NameComboBox
, to select the right Town
via its postalcode, but as the PostalCodeComboBox
is repeated for each item, I can't access it.
Any suggestions on how to get my PostalCodeComboBox
selecting the right PostalCode
as well?