【问题标题】:WPF Listbox - change itemsource of control in datatemplateWPF Listbox - 在数据模板中更改控件的项目源
【发布时间】:2009-09-11 10:08:20
【问题描述】:

我有一个带有数据模板的列表框,其中包含许多绑定到我的集合的控件。

我想要的是根据在同一行中的其他组合框之一中选择的值来更改这些组合框之一的 itemsource。我不想更改列表框中其余行中所有相应组合框的 itemsource。

如何仅获取所选行中控件的句柄。

使用 WPF 数据网格更容易尝试这样做吗?

谢谢。

【问题讨论】:

    标签: wpf datagrid listbox datatemplate


    【解决方案1】:

    使用 ListBox 实际上更容易,因为 DataTemplate 定义了一行的所有控件。

    我认为最简单的方法是在绑定上使用转换器。您将第二个 ComboBox 的 ItemsSource 绑定到第一个 ComboBox 的 SelectedItem:

    <myNamespace:MyConverter x:Key="sourceConverter" />
    
    <StackPanel Orientation="Horizontal>
        <ComboBox x:Name="cbo1" ... />
        ...
        <ComboBox ItemsSource="{Binding SelectedItem, ElementName=cbo1, Converter={StaticResource sourceConverter}}" ... />
        ...
    </StackPanel>
    

    请注意,如果您需要来自 Row 的 DataContext 的其他信息,可以将其设为 MultiBinding 和 IMultiValueConverter,并通过以下方式轻松传入 DataContext:

    <MultiBinding Converter="{StaticResource sourceConverter}">
        <Binding />
        <Binding Path="SelectedItem", ElementName="cbo1" />
    </MultiBinding>
    

    然后,在你的转换器类中,做任何你必须做的事情以获得正确的物品来源。

    【讨论】:

    • 非常感谢您的回复。这正是我一直在寻找的。我完全忽略了转换器 - 现在我可以想到很多可能性,我可以在哪里使用它们!
    【解决方案2】:

    获取该特定组合框的 SelectionChanged 事件并在该事件中设置另一个组合框的 Itemsource。

    private void cmb1SelectionChanged(object sender, SelectionChangedEventArgs e)
    {
      cmboBox2.ItemSource = yourItemSource;
    }
    

    另外最好是获取listview的SelectionChaged事件并处理。

     private void OnlistviewSelectionChanged( object sender, SelectionChangedEventArgs e )
     {
        // Handles the selection changed event so that it will not reflect to other user controls.
        e.Handled = true;
     }
    

    【讨论】:

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