Reset DataContext on ComboBox

  • Thread starter Thread starter Wonko the Sane
  • Start date Start date
W

Wonko the Sane

Hello,

I have a ComboBox that has a DataContext set on it. When a PropertyChanged
event is fired (based on a static instance of some class), I'd like to update
the DataContext on the combo, but it seems that I need to set it to null
first:

Combo1.DataContext = null;
Combo1.DataContext = dc;

If I don't set it to null first, the combo's Items count is 0.

Thanks,
WtS
 
Hello Paul,

Thanks for using Microsoft Newsgroup Support Service, my name is Ji Zhou
[MSFT] and I will be working on this issue with you.

Based on my understanding, the current issue is that we use the data
binding in WPF and update the comboBox's DataContext, but the data in the
comboBox does not get updated unless we set the DataContext to null first
and set it back. If any misunderstanding here, please feel free to correct
me.

Actually, if we update the DataContext's content, the comboBox will not
know it's DataContext has been changed. So, we will not see the combox
items' updating. The way to work around this problem is to implement
INotifyPropertyChanged for the data in the DataContext. I write the
following codes on my side which works fine:

In the WPF xaml file:

<Window x:Class="WpfApplication1.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Window1" Height="300" Width="300" Loaded="Window_Loaded">
<StackPanel>
<ComboBox Name="comboBox1" IsSynchronizedWithCurrentItem="True"

ItemsSource="{Binding}" DisplayMemberPath="CustomerName"/>
<Button Name="button1" Click="button1_Click">Button</Button>
</StackPanel>
</Window>

I create a MyCustomer class which implements the INotifyPropertyChanged
interface:

public class MyCustomer : INotifyPropertyChanged
{
private string customerName = String.Empty;

public event PropertyChangedEventHandler PropertyChanged;

private void NotifyPropertyChanged(String info)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(info));
}
}

public MyCustomer(string name)
{
this.customerName = name;
}

public string CustomerName
{
get { return this.customerName; }
set
{
if (value != this.customerName)
{
this.customerName = value;
NotifyPropertyChanged("customerName");
}
}
}
}

In the Window1.xaml.cs, I have the following codes. Whenever the button is
clicked, I update the dc's content and my combobox items get updated in the
UI.

public partial class Window1 : Window
{
ArrayList dc = new ArrayList();

public Window1()
{
InitializeComponent();
dc.Add(new MyCustomer("Ereka"));
dc.Add(new MyCustomer("Colbert"));
}

private void Window_Loaded(object sender, RoutedEventArgs e)
{
this.comboBox1.DataContext = dc;
}

private void button1_Click(object sender, RoutedEventArgs e)
{
(dc[0] as MyCustomer).CustomerName = "Tom";
}
}

Please let me know if the above suggestion works for your scenario or not.
And if you have any questions or concerns about this, please feel free to
post.

Best regards,
Ji Zhou ([email protected], remove 'online.')
Microsoft Online Community Support

Delighting our customers is our #1 priority. We welcome your comments and
suggestions about how we can improve the support we provide to you. Please
feel free to let my manager know what you think of the level of service
provided. You can send feedback directly to my manager at:
(e-mail address removed).

==================================================
Get notification to my posts through email? Please refer to
http://msdn.microsoft.com/en-us/subscriptions/aa948868.aspx#notifications.

Note: The MSDN Managed Newsgroup support offering is for non-urgent issues
where an initial response from the community or a Microsoft Support
Engineer within 1 business day is acceptable. Please note that each follow
up response may take approximately 2 business days as the support
professional working with you may need further investigation to reach the
most efficient resolution. The offering is not appropriate for situations
that require urgent, real-time or phone-based interactions or complex
project analysis and dump analysis issues. Issues of this nature are best
handled working with a dedicated Microsoft Support Engineer by contacting
Microsoft Customer Support Services (CSS) at
http://support.microsoft.com/select/default.aspx?target=assistance&ln=en-us.
==================================================
This posting is provided "AS IS" with no warranties, and confers no rights.
 
Hi Zhou,

Thank you - that essentially answers my question. However, I do see an
issue if I take your example a little further. I added some buttons with
event handlers:


[Window1.xaml]
<StackPanel>
<ComboBox Name="comboBox1" IsSynchronizedWithCurrentItem="True"

ItemsSource="{Binding}" DisplayMemberPath="CustomerName"/>

<Button Name="button1" Click="button1_Click">Change First
Item</Button>
<Button Name="button2" Click="button2_Click">Add One Item</Button>
<Button Name="button3" Click="button3_Click">Add Items, No
Null</Button>
<Button Name="button4" Click="button4_Click">Add Items, Null
dc</Button>
</StackPanel>

[Window1.xaml.cs]
private void button2_Click(object sender, RoutedEventArgs e)
{
dc.Add(new MyCustomer("Yin"));
this.comboBox1.DataContext = dc;
}

private void button3_Click(object sender, RoutedEventArgs e)
{
dc.Add(new MyCustomer("Smooshie"));
dc.Add(new MyCustomer("Jacko"));
dc.Add(new MyCustomer("Fisher"));
this.comboBox1.DataContext = dc;
this.comboBox1.SelectedIndex = 3;
}

private void button4_Click(object sender, RoutedEventArgs e)
{
dc.Add(new MyCustomer("Ralph"));
dc.Add(new MyCustomer("Spencer"));
dc.Add(new MyCustomer("Lulu"));
this.comboBox1.DataContext = null;
this.comboBox1.DataContext = dc;
this.comboBox1.SelectedIndex = 4;
}


If I press button 2 to add a single customer, and then press button 3 to add
other customers, I will see the customer as specified in the SelectedIndex.
However, if you drop down the combo, only the original 3 (sometimes, only the
original 2) items are shown. None of the new customers added in the button3
handler are shown.

If you run the application again, and this time choose button 4 instead of
button 3, you will see all of the customers when expanding the combo. The
only difference is that I set the DataContext to null before setting it to
the updated ArrayList.

Thanks,
Paul
 
Hello Paul,

In order to set up dynamic bindings so that insertions or deletions in the
collection update the UI automatically, the collection must implement
another interface INotifyCollectionChanged. Thanks to the
ObservableCollection<T> class provided by WPF which has already implemented
the INotifyCollectionChanged interface, we can achieve our objective easily
by inheriting our collection class from it.

I modify the codes in Window1.xaml.cs as follows. The CustomerList
implements the InotifyCollectionChanged interface, so when we add or delete
items from the collection instance, the UI will get updated automatically.
We do not need to set the dc to null and back in our codes now. In fact,
the InotifyCollectionChanged to the CustomerList collection class is
similar as the InotifyPropertyChanged to the MyCustomer class.

public class CustomerList :
System.Collections.ObjectModel.ObservableCollection<MyCustomer>
{
public CustomerList() : base()
{
}
}

public partial class Window1 : Window
{
CustomerList dc = new CustomerList();

public Window1()
{
InitializeComponent();
dc.Add(new MyCustomer("Ereka"));
dc.Add(new MyCustomer("Colbert"));
}

private void Window_Loaded(object sender, RoutedEventArgs e)
{
this.comboBox1.DataContext = dc;
}

private void button1_Click(object sender, RoutedEventArgs e)
{
(dc[0] as MyCustomer).CustomerName = "Grace";
}

private void button2_Click(object sender, RoutedEventArgs e)
{
dc.Add(new MyCustomer("Yin"));
}

private void button3_Click(object sender, RoutedEventArgs e)
{
dc.Add(new MyCustomer("Smooshie"));
dc.Add(new MyCustomer("Jacko"));
dc.Add(new MyCustomer("Fisher"));
}

private void button4_Click(object sender, RoutedEventArgs e)
{
dc.Add(new MyCustomer("Ralph"));
dc.Add(new MyCustomer("Spencer"));
dc.Add(new MyCustomer("Lulu"));
}
}

If you have any other questions or concerns, please feel free to post. I am
glad to be of future assistance.

Best regards,
Ji Zhou ([email protected], remove 'online.')
Microsoft Online Community Support

Delighting our customers is our #1 priority. We welcome your comments and
suggestions about how we can improve the support we provide to you. Please
feel free to let my manager know what you think of the level of service
provided. You can send feedback directly to my manager at:
(e-mail address removed).

This posting is provided "AS IS" with no warranties, and confers no rights.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Back
Top