【问题标题】:Find a control within a ListViewItem在 ListViewItem 中查找控件
【发布时间】:2011-07-18 20:02:12
【问题描述】:

我有一个 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>

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

你能告诉我如何进行吗?

【问题讨论】:

  • 你不能在你的代码隐藏中简单地引用combo2吗?
  • 我不能,因为ListView 中的每一行都有一个具有此名称的实例@

标签: c# wpf xaml


【解决方案1】:

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

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

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

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

或者,您可以从Parent 属性中获取StackPanel,然后只需获取(ComboBox)Children[1]。如果你的模板结构发生变化,我不会这样做。

【讨论】:

    【解决方案2】:

    你不应该有对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;
    }
    

    【讨论】:

    • 你不能,因为它会更新每个项目的combo2 的来源。
    【解决方案3】:

    可以在这里查看我的问题和不同的回答以及我为我的特定项目找到的解决方案:

    Find an element in Data Template

    希望这会有所帮助。

    问候。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-01-31
      • 1970-01-01
      • 2011-09-28
      • 1970-01-01
      • 1970-01-01
      • 2011-12-07
      • 2011-05-05
      相关资源
      最近更新 更多