views:

18

answers:

1

Hi.
I am currently experimenting with WPF. One thing, I wanted to do was a master to detail selection over multiple comboboxes. I have a ViewModel with GroupItems that i use as ItemSource for the first combobox. These GroupItems have a Property called Childs, which includes a List of items that belong to this group.

I can't find a way to bind the comboBox1.SelectedItem.Childs as Itemsource for the second comboBox.

Right now I only got to

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

But I don't get the Property of the SelectedItem. How can this be done? Or is this not the WPF way to this?

Is there any good website to learn how to select different elements? Eplaining Path, XPath, Source and everything?

Thanks for any help.

+1  A: 

Your binding above isn't attempting to bind to Childs, only SelectedItem.

Try something like this:

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

ViewModel.cs

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