代码之家  ›  专栏  ›  技术社区  ›  Marks

绑定到SelectedItem属性的属性

  •  1
  • Marks  · 技术社区  · 15 年前

    我目前正在试验WPF。 有一件事,我想做的是在多个组合框上进行一个从主到细的选择。 我有一个带有GroupItems的ViewModel,用作第一个组合框的ItemSource。这些GroupItems有一个名为Childs的属性,其中包含属于此组的项的列表。

    我找不到将comboBox1.SelectedItem.Childs绑定为第二个组合框的Itemsource的方法。

    现在我只需要

    ItemsSource="{Binding ElementName=comboBox1, Path=SelectedItem}"
    

    但我不知道SelectedItem的属性。如何做到这一点?或者这不是WPF的方法?

    谢谢你的帮助。

    1 回复  |  直到 15 年前
        1
  •  2
  •   lesscode    15 年前

    上面的绑定没有尝试绑定到Childs,只是SelectedItem。

    尝试以下操作:

    窗口1.xaml

    <Window x:Class="WpfApplication5.MainWindow"
            xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
            xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
            Title="MainWindow" Height="350" Width="525">
        <StackPanel>
            <ComboBox x:Name="_groups" ItemsSource="{Binding Groups}" DisplayMemberPath="Name"/>
            <ComboBox ItemsSource="{Binding SelectedItem.Items, ElementName=_groups}"/>
        </StackPanel>
    </Window>
    

    Window1.xaml.cs

    using System.Windows;
    
    namespace WpfApplication5 {
        /// <summary>
        ///   Interaction logic for MainWindow.xaml
        /// </summary>
        public partial class MainWindow : Window {
            public MainWindow() {
                InitializeComponent();
    
                var model = new ViewModel();
    
                var g1 = new Group { Name = "Group1" };
                g1._items.Add("G1C1");
                g1._items.Add("G1C2");
                g1._items.Add("G1C3");
                model._groups.Add(g1);
    
                var g2 = new Group { Name = "Group2" };
                g2._items.Add("G2C1");
                g2._items.Add("G2C2");
                g2._items.Add("G2C3");
                model._groups.Add(g2);
    
                var g3 = new Group { Name = "Group3" };
                g3._items.Add("G3C1");
                g3._items.Add("G3C2");
                g3._items.Add("G3C3");
                model._groups.Add(g3);
    
                DataContext = model;
            }
        }
    }
    

    using System;
    using System.Collections.Generic;
    
    namespace WpfApplication5
    {
        public class Group {
            internal List<String> _items = new List<string>();
            public IEnumerable<String> Items {
                get { return _items; }
            }
            public String Name { get; set; }
        }
        public class ViewModel
        {
            internal List<Group> _groups = new List<Group>();
            public IEnumerable<Group> Groups
            {
                get { return _groups; }
            }
        }
    }