Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 5949695
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 22, 20262026-05-22T17:17:11+00:00 2026-05-22T17:17:11+00:00

I am trying to grasp the concepts of WPF data binding through a simple

  • 0

I am trying to grasp the concepts of WPF data binding through a simple example, but it seems I haven’t quite gotten the point of all of it.

The example is one of cascading dropdowns; the XAML is as follows:

<Window x:Class="CascadingDropDown.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="496" Width="949" Loaded="Window_Loaded">
    <Grid>
        <ComboBox Name="comboBox1" ItemsSource="{Binding}" DisplayMemberPath="Key" SelectionChanged="comboBox1_SelectionChanged" />
        <ComboBox Name="comboBox2" ItemsSource="{Binding}" DisplayMemberPath="Name" />
    </Grid>
</Window>

This is the code of the form:

public partial class MainWindow : Window
{
    private ObservableCollection<ItemA> m_lstItemAContext = new ObservableCollection<ItemA>();
    private ObservableCollection<ItemB> m_lstItemBContext = new ObservableCollection<ItemB>();
    private IEnumerable<ItemB> m_lstAllItemB = null;

    public MainWindow()
    {
        InitializeComponent();

        this.comboBox1.DataContext = m_lstItemAContext;
        this.comboBox2.DataContext = m_lstItemBContext;
    }

    private void Window_Loaded(object sender, RoutedEventArgs e)
    {
        var lstItemA = new List<ItemA>() { new ItemA("aaa"), new ItemA("bbb"), new ItemA("ccc") };
        var lstItemB = new List<ItemB>() { new ItemB("aaa", "a11"), new ItemB("aaa", "a22"), new ItemB("bbb", "b11"), new ItemB("bbb", "b22") };

        initPicklists(lstItemA, lstItemB);
    }

    private void initPicklists(IEnumerable<ItemA> lstItemA, IEnumerable<ItemB> lstItemB)
    {
        this.m_lstAllItemB = lstItemB;

        this.m_lstItemAContext.Clear();
        lstItemA.ToList().ForEach(a => this.m_lstItemAContext.Add(a));
    }

    #region Control event handlers

    private void comboBox1_SelectionChanged(object sender, SelectionChangedEventArgs e)
    {
        ComboBox ddlSender = (ComboBox)sender;
        ItemA itemaSelected = (ItemA)ddlSender.SelectedItem;

        var lstNewItemB = this.m_lstAllItemB.Where(b => b.KeyA == itemaSelected.Key);

        this.m_lstItemBContext.Clear();
        lstNewItemB.ToList().ForEach(b => this.m_lstItemBContext.Add(b));
    }

    private void comboBox2_?(object sender, ?EventArgs e)
    {
        // disable ComboBox  if empty
    }
    #endregion Control event handlers
}

And these are my data classes:

class ItemA
{
    public string Key { get; set; }

    public ItemA(string sKey)
    {
        this.Key = sKey;
    }
}

class ItemB
{
    public string KeyA { get; set; }

    public string Name { get; set; }

    public ItemB(string sKeyA, string sName)
    {
        this.KeyA = sKeyA;
        this.Name = sName;
    }
}

So whenever an item is selected in comboBox1, the appropriate items are supposed to show up in comboBox2. This is working with the current code, though I’m not sure whether my way of re-populating the respective ObservableCollection is ideal.

What I haven’t been able to achieve is actually reacting to changes in the underlying collection of comboBox2, for example to deactivate the control when the list is empty (i.e. when “ccc” is selected in comboBox1).

Of course, I can use an event handler on the CollectionChanged event of the ObservableCollection, and that would work in this example, but in a more complex scenario, where the ComboBox’ DataContext might change to a completely different object (and possibly back), that would mean a two-fold dependency – I would always have to not only switch the DataContext, but also the event handlers back and forth. This doesn’t seem right to me, but I am probably simply on an entirely wrong track about this.

Basically, what I am looking for is an event firing on the control rather than the underlying list; not the ObservableCollection announcing “my contents have changed”, but the ComboBox telling me “something happenend to my items”.

What do I need to do, or where do I have to correct my perception of the whole concept ?

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-22T17:17:12+00:00Added an answer on May 22, 2026 at 5:17 pm

    Here is the cleaner (perhaps not the much optimized) way to acheive this, keeping your business model untouched, and using ViewModel and XAML only when possible :

    View Model :

    public class WindowViewModel : INotifyPropertyChanged
    {
        private ItemA selectedItem;
    
    
        private readonly ObservableCollection<ItemA> itemsA = new ObservableCollection<ItemA>();
        private readonly ObservableCollection<ItemB> itemsB = new ObservableCollection<ItemB>();
        private readonly List<ItemB> internalItemsBList = new List<ItemB>();
    
    
        public WindowViewModel()
        {
            itemsA = new ObservableCollection<ItemA> { new ItemA("aaa"), new ItemA("bbb"), new ItemA("ccc") };
            InvokePropertyChanged(new PropertyChangedEventArgs("ItemsA"));
    
            internalItemsBList = new List<ItemB> { new ItemB("aaa", "a11"), new ItemB("aaa", "a22"), new ItemB("bbb", "b11"), new ItemB("bbb", "b22") };
    
        }
    
        public ObservableCollection<ItemA> ItemsA
        {
            get { return itemsA; }
        }
    
        public ItemA SelectedItem
        {
            get { return selectedItem; }
    
            set
            {
                selectedItem = value;
    
                ItemsB.Clear();
                var tmp = internalItemsBList.Where(b => b.KeyA == selectedItem.Key);
                foreach (var itemB in tmp)
                {
                    ItemsB.Add(itemB);
                }
    
    
                InvokePropertyChanged(new PropertyChangedEventArgs("SelectedItem"));
            }
        }
    
        public ObservableCollection<ItemB> ItemsB
        {
            get { return itemsB; }
        }
    
        public event PropertyChangedEventHandler PropertyChanged;
    
        public void InvokePropertyChanged(PropertyChangedEventArgs e)
        {
            PropertyChangedEventHandler handler = PropertyChanged;
            if (handler != null) handler(this, e);
        }
    }
    

    Code Behind :

    public partial class Window1
    {
        public Window1()
        {
            InitializeComponent();
            DataContext = new WindowViewModel();
        }
    }
    

    and XAML :

     <StackPanel>
        <ComboBox Name="comboBox1" ItemsSource="{Binding ItemsA}" DisplayMemberPath="Key" SelectedItem="{Binding SelectedItem, Mode=TwoWay}"  />
        <ComboBox Name="comboBox2" ItemsSource="{Binding ItemsB}" DisplayMemberPath="Name">
            <ComboBox.Style>
                <Style TargetType="{x:Type ComboBox}">
                    <Setter Property="IsEnabled" Value="true"/>
                    <Style.Triggers>
                        <DataTrigger Binding="{Binding ItemsB.Count}" Value="0">
                            <Setter Property="IsEnabled" Value="false"/>
                        </DataTrigger>
                    </Style.Triggers>
                </Style>
            </ComboBox.Style>
        </ComboBox>
    </StackPanel>
    

    copying-pasting this should work.

    Few random thoughts :

    1) in WPF, try to always use MVVM pattern and never put code in code-behind files for event handlers. For user actions (like button clicks) use the Commands pattern. For other user actions for which commands are not available, think as much as you can in a “binding-way” : you can do a lot since you can intercept event from the view in VM properties setters (in your example I use the SelectedItem property setter).

    2) Use XAML as much as you can. WPF framework provides a very powerful binding and triggers system (in your example, the enabling of combobox don’t needs any line of C#).

    3) ObservableCollection are made to be exposed by the view model to the view via binding. They are also meant to be used in conjunction with their CollectionChanged event that you can handle in the view model. Take benefit of that (in your example, I play with Observable collection in the VM, where this playing should happen, and any changes in the collection gets reflected in the view via DataBinding).

    Hopes this will help !

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I've been reading the javadocs trying to grasp around the swing Document API but
I'm new to the MVC pattern but have been trying to grasp it, for
Given an example like this: class MyForm(forms.Form): name = forms.CharField() I'm trying to grasp
Ok, so I'm trying to grasp the concept of WPF Commands. They seem pretty
I am a little new to .net and trying to grasp a few concepts.
I am a CS student trying to grasp some C++ basic concepts. I am
I'm really new to DDD and trying to grasp some of the concepts. Could
Can't see the trees through the forest. Trying a simple databinding and I want
I'm trying to grasp the concept of continuations and I found several small teaching
I'm trying to grasp the concept of .NET Generics and actually use them in

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.