在ListViewItem中查找控件

时间:2011-07-18 08:47:51

标签: c# wpf xaml

我有ListView显示主要包含两个属性的项目列表。

理想情况下,每个属性都应从两个组合框中选择。

此外,第二个组合框中可用的选项取决于第一个。

所以这是我使用的代码的想法:

<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>

问题是,我不知道如何从combo2(在C#中)获取对combo_SelectionChanged的引用。

你能告诉我怎么办吗?

3 个答案:

答案 0 :(得分:1)

你不应该引用combo2,但是你应该更新Collection combo2Source,它被绑定为combo2的ItemsSource ...

因此,在combo_SelectionChanged中,您只需将实际选择的combo1的可能值加载到combo2Source集合。

编辑:为了防止它对所有项目都相同:

添加一个ValueConverter,为selectedItem选择相应的可能值集合:

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

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;
}

答案 1 :(得分:1)

您可以做的最简单的事情是向Tag添加combo1

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

然后您可以从事件处理程序中的sender获取,例如

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

或者,您可以从StackPanel媒体资源中获取Parent,然后点击(ComboBox)Children[1]。如果模板的结构发生变化,我不会这样做。

答案 2 :(得分:0)

可以看一下我的问题和不同的回答以及我为我的具体项目找到的解决方案:

Find an element in Data Template

希望这有帮助。

问候。