473,612 Members | 2,129 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Binding to INotifyCollecti onChanged event

I am trying to bind a WPF dependency property to an aggregate of a
collection. I've implemented a wrapper around a Dictionary that
implements INotifyCollecti onChanged to fire the event when items are
added or removed.

Debugging through it I notice that there is nothing listening to the
event after I bind to it which I expected the SetBinding to do as I
don't know what delegate to attach to the event. It's the binding that
needs updating after all.

I've tried a test with just an ObservableColle ction to see if I was
missing something but that doesn't work either.

How do I wire up the event to the binding or do whatever it takes to
get my test to pass?

Here's my test code:

[TestClass()]
public class ObservableDicti onaryTest : DependencyObjec t
{
public class MaxDoubleConver ter : IValueConverter
{
public object Convert(object value, Type targetType, object
parameter, System.Globaliz ation.CultureIn fo culture)
{
if (value is IEnumerable<dou ble>)
{
return ((IEnumerable<d ouble>)value).M ax(); // using
Linq
}

throw new ArgumentExcepti on("Cannot covert " +
value.GetType() + " to IEnumerable<dou ble>", "value");
}
public object ConvertBack(obj ect value, Type targetType,
object parameter, System.Globaliz ation.CultureIn fo culture)
{
throw new NotImplementedE xception();
}
}

public double Max
{
get { return (double)GetValu e(MaxProperty); }
}

public static readonly DependencyPrope rty MaxProperty =
DependencyPrope rty.Register("M ax", typeof(double),
typeof(Observab leDictionaryTes t), new PropertyMetadat a(0.0));

[TestMethod()]
public void TestBindingToOb servableCollect ion()
{
ObservableColle ction<doubleval ues = new
ObservableColle ction<double>() ;
values.Add(1.0) ;
values.Add(2.0) ;
values.Add(3.0) ;

Binding b = new Binding();
b.Converter = new MaxDoubleConver ter();
b.Source = values;
b.Mode = BindingMode.One Way;
BindingOperatio ns.SetBinding(t his, MaxProperty, b);

Assert.AreEqual (3.0, Max); // this works

values.Add(4.0) ;
Assert.AreEqual (4.0, Max); // this doesn't

values.Remove(4 .0);
Assert.AreEqual (3.0, Max);
}
}
Jun 27 '08 #1
7 7998
What about using ObservableColle ction<T>?

--
Pete
=============== =============== ===========
I use Enterprise Core Objects (Domain driven design)
http://www.capableobjects.com/
=============== =============== ===========
Jun 27 '08 #2
On 9 Jun, 16:22, "Peter Morris" <mrpmorris at gmail dot comwrote:
What about using ObservableColle ction<T>?

--
Pete
=============== =============== ===========
I use Enterprise Core Objects (Domain driven design)http://www.capableobjects.com/
=============== =============== ===========
That's what the test I've posted does or do you mean use it in another
way? It's only my test class that is called ObservableDicti onaryTest
(maybe I should have renamed it if that caused confusion).

I'd expect the Binding.Source setter to check if the source is
IEnumerable and if it implements INotifyCollecti onChanged then listen
to the event and update the bound value when it fires.

I'm obviously not understanding how binding to an ObservableColle ction
works.

Jun 27 '08 #3
>I am trying to bind a WPF dependency property to an aggregate of a
collection. I've implemented a wrapper around a Dictionary that
implements INotifyCollecti onChanged to fire the event when items are
added or removed.

Debugging through it I notice that there is nothing listening to the
event after I bind to it which I expected the SetBinding to do as I
don't know what delegate to attach to the event. It's the binding that
needs updating after all.

I've tried a test with just an ObservableColle ction to see if I was
missing something but that doesn't work either.

How do I wire up the event to the binding or do whatever it takes to
get my test to pass?
I think the problem is that only bindings which expect to bind to a
collection (like ListBox.ItemsSo urce) check for and subscribe to
INotifyCollecti onChanged (though I don't know exactly how they do it).

What you could do is make your collection a property of your class, bind to
the property, implement INotifyProperty Changed, then subscribe to the
collection's INotifyCollecti onChanged yourself and raise a PropertyChanged
event. This seems rather clumsy and I'm sure there ought to be a better
way - maybe someone more knowledgeable will point it out.

Chris Jobson
Jun 27 '08 #4
On 9 Jun, 17:54, "Chris Jobson" <chris.job...@b tinternet.comwr ote:
I am trying to bind a WPF dependency property to an aggregate of a
collection. I've implemented a wrapper around a Dictionary that
implements INotifyCollecti onChanged to fire the event when items are
added or removed.
Debugging through it I notice that there is nothing listening to the
event after I bind to it which I expected the SetBinding to do as I
don't know what delegate to attach to the event. It's the binding that
needs updating after all.
I've tried a test with just an ObservableColle ction to see if I was
missing something but that doesn't work either.
How do I wire up the event to the binding or do whatever it takes to
get my test to pass?

I think the problem is that only bindings which expect to bind *to a
collection (like ListBox.ItemsSo urce) check for and subscribe to
INotifyCollecti onChanged (though I don't know exactly how they do it).

What you could do is make your collection a property of your class, bind to
the property, implement INotifyProperty Changed, then subscribe to the
collection's INotifyCollecti onChanged yourself and raise a PropertyChanged
event. This seems rather clumsy and I'm sure there ought to be a better
way - maybe someone more knowledgeable will point it out.

Chris Jobson
Thanks.

One other idea I had was that it was the DependencyPrope rty that
needed refreshing so I tried subscribing to the event and calling
InvalidatePrope rty(MaxProperty ), but that didn't work either, it still
came out as 3.0 somehow and the Convert was never called again so the
3.0 isn't being invalidated.

I'll try your idea since the collection will be a property of a
UserControl once I get it working.
Jun 27 '08 #5
>I am trying to bind a WPF dependency property to an aggregate of a
collection. I've implemented a wrapper around a Dictionary that
implements INotifyCollecti onChanged to fire the event when items are
added or removed.

Debugging through it I notice that there is nothing listening to the
event after I bind to it which I expected the SetBinding to do as I
don't know what delegate to attach to the event. It's the binding that
needs updating after all.

I've tried a test with just an ObservableColle ction to see if I was
missing something but that doesn't work either.

How do I wire up the event to the binding or do whatever it takes to
get my test to pass?
I think the problem is that only bindings which expect to bind to a
collection (like ListBox.ItemsSo urce) check for and subscribe to
INotifyCollecti onChanged (though I don't know exactly how they do it).

What you could do is make your collection a property of your class, bind to
the property, implement INotifyProperty Changed, then subscribe to the
collection's INotifyCollecti onChanged yourself and raise a PropertyChanged
event. This seems rather clumsy and I'm sure there ought to be a better
way - maybe someone more knowledgeable will point it out.

Chris Jobson
Jun 27 '08 #6
After looking into this a bit more I found
http://www.drwpf.com/Blog/Default.as...=36&EntryID=18 that told
me that it is a CollectionView that does the subscribing to
CollectionChang ed in ListBox and the like.

Naturally I tried wrapping my collection in a CollectionView and
setting that as the source but now the Max property doesn't get
evaluated at all (my converter is never called) so thebinding is
treating the view differently to any other plain IEnumerable, like it
thinks it doesn't need to do anything if it already has a
CollectionView.

This seems like one of those times when I'm digging deeper than I need
to and all this clever Binding and CollectionView stuff does what I
need if only I knew how to use it properly.
Jun 27 '08 #7
After looking into this a bit more I found
http://www.drwpf.com/Blog/Default.as...=36&EntryID=18 that told
me that it is a CollectionView that does the subscribing to
CollectionChang ed in ListBox and the like.
Thanks for that link. I'd read it some time ago but had forgotten the bit
about CollectionView.
Naturally I tried wrapping my collection in a CollectionView and
setting that as the source but now the Max property doesn't get
evaluated at all (my converter is never called) so thebinding is
treating the view differently to any other plain IEnumerable, like it
thinks it doesn't need to do anything if it already has a
CollectionView.
I *think* (but could well be wrong - I find it all a bit confusing!) it's
still the same problem - binding Max to a CollectionView is more or less the
same as binding it to an ObservableColle ction, and in both cases a change to
the collection won't re-evaluate Max because it isn't interested in
INotifyCollecti onChanged. AIUI the special feature of CollectionView is that
it if your property is of type CollectionView then you can bind a collection
to it and the property will re-evaluate when the collection changes.

(By the way, I'm surprised your idea of InvalidatePrope rty(MaxProperty )
didn't work. I've never used InvalidatePrope rty myself, but from the
description in MSDN it sounds ideal.)

I've just come across what might be another solution to your problem -
BindableLINQ (http://www.codeplex.com/bindablelinq/). In particular this
post (http://www.paulstovell.com/blog/bind...ble-aggregates)
seems to describe something very similar to your requirement. It's only a
beta, and I've no experience of it myself, but it might be worth
investigating.

Chris
Jun 27 '08 #8

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

3
2755
by: Rodrigo Benenson | last post by:
Hi, I have a weird need in tkinter. If I have a widget I can *set* a binding ..bind("<the event>", the_callback) I also can *append* a binding ..bind("<the event>", the_second_callback, "+")
1
281
by: Marcin Floryan | last post by:
Hello! My question regards opening (and re-opening) Form and the Load event. I have a main form (frmMain) and I also have a data form (frmData). In the main form I have created: Private fData as new frmData()
1
5885
by: Jonathan Yong | last post by:
I observe a very weird behavior when dynamically create web control and bind events to it. Create a C# ASP.NET application, Put a PlaceHolder and Textbox onto the Web form, and try with the 4 code scenerio below. --------------------------------------------------------------------------- Scenerio 1
11
4650
by: Rourke Eleven | last post by:
I have looked and searched. What good is the databind property on Radiobuttons? How does one go about actually using it? What is a good resource on this? I understand that I can easily get/set the information I need programmatically, but what about the databind property I just don't understand it's value.
19
2331
by: Simon Verona | last post by:
I'm not sure if I'm going down the correct route... I have a class which exposes a number of properties of an object (in this case the object represents a customer). Can I then use this object to databind to text boxes etc? I can't use a dataset as the object has loads of derived logic, for example updating one property may actually update several database fields for example.
0
1517
by: Larry Serflaten | last post by:
I am not sure how many are aware of this sort of data binding, but as it is new to many (classic) VB developers I thought I would post this once just to let people know of its availablility. There are cases where properties of one object is dependant on a property of another object. For a common example, when you bind an ArrayList to a ComboBox using the combo's DataSource property, the combo box fills up with items from the array list....
13
2402
by: Michael.Suarez | last post by:
Let's suppose I have an instance of MyClass, which has the properties MyText1 and MyText2, and sets the values of MyText1 and MyText2 to 'A' and 'B' in it's constructor. Let's also suppose I have a Form with textBox1, textBox2, btnShowValue, and btnNew. Let's also suppose I have this code. //member of Form
6
2442
by: Mikus Sleiners | last post by:
Is there any way to enable exception throws in VS 2005, that occur during binding operations? I am upset that i can't see exceptions that are thrown during binding operations. It's very hard to track down erroneous behaviour of your app if you can't see where the problem is... i mean it's realy hard to debug binding issues and it would be realy of help if i could somehow enable this during debug session.
6
2896
by: Dmitry Duginov | last post by:
Hi, I have the following label markup (label is inside FormView): <asp:Label ID="lblIndicatorReady" runat="server" Text="RE" ToolTip="Ready" BackColor='<%# Eval("Ready").ToString()=="True"?System.Drawing.Color.FromName("#FFFF80"):System.Drawing.Color.White %>' Enabled='<%# Eval("Ready") %>'
0
8605
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
1
8246
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
8415
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
7039
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
6076
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5532
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4109
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
2550
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
1
1695
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.