SRKX
SRKX

Reputation: 1826

Find a control within a ListViewItem

I have a ListView displaying a list of items containing mainly two properties.

Each of these properties should ideally be chosen from two comboboxes.

Moreover, the choices available in the second combobox is depends on the first.

So here is the idea of the code I used:

<ListView>
   <ListView.ItemTemplate>
       <DataTemplate>
          <StackPanel>
              <ComboBox Name="combo1"
                        ItemsSource="{DynamicResource combo1Source}"
                        SelectedItem="{Binding FirstProperty}"
                        SelectionChanged="combo_SelectionChanged">
              <ComboBox Name="combo2"
                        ItemsSource="{DynamicResource combo2Source}"
                        SelectedItem="{Binding SecondProperty}">
          </StackPanel>
       <DataTemplate>
   <ListView.ItemTemplate>
</ListView>

The thing is, I don't know how to get the reference to combo2 from within combo_SelectionChanged (in C#).

Could you show me how to proceed?

Upvotes: 0

Views: 1450

Answers (3)

brunnerh
brunnerh

Reputation: 185553

The easiest thing you can do is add a Tag to combo1:

 <ComboBox Name="combo1" Tag="{x:Reference combo2}" ... />

Which you then can just get from the sender in the event handler, e.g.

var combo2 = (sender as FrameworkElement).Tag as ComboBox;

Alternatively you could get the StackPanel from the Parent property and just take (ComboBox)Children[1]. I would not do this though as is breaks if the structure of your template changes.

Upvotes: 1

fixagon
fixagon

Reputation: 5566

You should not have a reference to combo2, but you should update the Collection combo2Source which is bound as ItemsSource for combo2...

So in the combo_SelectionChanged you just load the possible values for the actual selection of combo1 to the combo2Source Collection.

EDIT: To prevent thats its for all items the same:

Add a ValueConverter which choses for a selectedItem the corresponding collection of possible values:

<ComboBox ItemsSource="{Binding ElementName=Combo1, Path=SelectedItem, Converter={StaticResource SubSelectionConverter}}" />

Example of ValueConverter:

private Dictionary<Object, List<Object>> _PossibleValues;
public object Convert(Object data, ....)
{
   if(PossibleValues.ContainsKey(data))
   {
      //return the possible values for the actual selected parent item
      return(PossibleValues(data));
   }
   return null;
}

Upvotes: 1

Tigran
Tigran

Reputation: 62265

Can have look here on my question and different responses and the solution I found for my specific project:

Find an element in Data Template

Hope this helps.

Regards.

Upvotes: 0

Related Questions