Subscribing To The Self Tracking Entities PropertyChanged Event - c#

I am writing a WPF application using Self-Tracking Entities. I'm having trouble Disabling/Enabling my Save button as my Model's values are changed. Normally with the regular Entity Framework Model I am able to simply subscribe to the Model.PropertyChanged event in my ViewModel, then RaisePropertyChanged for my Save Button, which checks validation and Disabled or Enables my save button.
For some reason, with Self-Tracking Entities I noticed that the Model.PropertyChanged event is marked as protected, so I am unable to subscribe to it directly in my ViewModel. Is there any way to subscribe to this event without modifying the T4 Template??
protected virtual void OnPropertyChanged(String propertyName)
{
if (ChangeTracker.State != ObjectState.Added && ChangeTracker.State != ObjectState.Deleted)
{
ChangeTracker.State = ObjectState.Modified;
}
if (_propertyChanged != null)
{
_propertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
protected virtual void OnNavigationPropertyChanged(String propertyName)
{
if (_propertyChanged != null)
{
_propertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
event PropertyChangedEventHandler INotifyPropertyChanged.PropertyChanged{ add { _propertyChanged += value; } remove { _propertyChanged -= value; } }
private event PropertyChangedEventHandler _propertyChanged;
private ObjectChangeTracker _changeTracker;

I've always just modified the template to make it not protected. It's a template for a reason :)
I suppose an alternative would be to create a public method on your class which raises the PropertyChanged notification internally.
partial class MyModel
{
public RaiseEFPropertyChanged(string propertyName)
{
RaisePropertyChanged(propertyName);
}
}

Related

How do I find out who has subscribed to an event field?

I want to find out when the PropertyChanged event handler is set in my base class.
Both Debug.Print("Is Null") and Debug.Print("not null") get hit. So it must get set somewhere.
How do I find that out?
A search for PropertyChanged does not reveal code that subscribes to the ebvent.
public abstract class NonPersistentObjectBase : INotifyPropertyChanged, IObjectSpaceLink {
public event PropertyChangedEventHandler PropertyChanged; // how do I break here
protected void OnPropertyChanged(string propertyName) {
if(PropertyChanged != null) {
Debug.Print("not null"); // gets hit after I click save
}
else {
Debug.Print("Is Null"); //gets hit
}
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
protected void SetPropertyValue<T>(string name, ref T field, T value) {
if(!Equals(field, value)) {
field = value;
OnPropertyChanged(name);
}
}
I added a private event as per Olivier's suggestion but am unsure how to call it.
I tried assigning it in the constructor
private event PropertyChangedEventHandler PropertyChangedAdd {
add => PropertyChanged += value;
remove => PropertyChanged -= value;
}
We cannot add a breakpoint to such a single statement without an assignment.
We can only add on a runtime instruction.
A void declaration as well as a method signature alone is not an real instruction to be executed: no assignment, no call, no loop, no test, no jump, no calculation... just a "static memory reservation" planned and done by the compiler at compile-time.
But we can implement add and remove accessors of a property-event on a real private field, thus we will be able to put breakpoints.
Also, once that done, we can open the call stack window in Visual Studio or go out of the method toward the caller subscriber.
public event PropertyChangedEventHandler PropertyChanged
{
add => _PropertyChanged += value;
remove => _PropertyChanged -= value;
}
private event PropertyChangedEventHandler _PropertyChanged

WPF: Best way to block OnPropertyChanged

I have implemented WPF data binding with INotifyPropertyChanged.
public class ExportNode : INotifyPropertyChanged
{
public uint Handle { get; set; }
public String Text { get; set; }
private bool _ischecked;
public bool IsChecked
{
get
{
return _ischecked;
}
set
{
_ischecked = value;
OnPropertyChanged("IsChecked");
}
}
public event PropertyChangedEventHandler PropertyChanged;
// Create the OnPropertyChanged method to raise the event
protected void OnPropertyChanged(string name)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null)
{
handler(this, new PropertyChangedEventArgs(name));
}
}
}
And than subscribing to event form my code, so whenever I change property in UI, it fires callback.
But now I'm trying to figure out the best way to change property from code, and than not fire callback, just update UI.
void newNode_PropertyChanged(object sender, PropertyChangedEventArgs e)
{
if (e.PropertyName == "IsChecked")
{
}
}
For now I just thought about implementing some "blocker" member property in ExportNode
protected void OnPropertyChanged(string name)
{
if (Blocked)
return;
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null)
{
handler(this, new PropertyChangedEventArgs(name));
}
}
or delete event form instance before change.
newNode.PropertyChanged -= newNode_PropertyChanged;
newNode.IsChecked = true;
newNode.PropertyChanged += newNode_PropertyChanged;
But is there any better way? I just don't understand some basics? :-)
Thank you very much
Roman
You've got this a little backwards.
INotifyPropertyChanged, and thus the PropertyChanged event, is what makes the UI update, in fact, its what makes the whole binding system work.
So to update the UI, you have to raise that event. Now, from the code side, you almost never subscribe to that event, because you could just invoke a method from the setter. Something like:
set
{
_ischecked = value;
OnPropertyChanged("IsChecked");
if (!Blocked)
MyOtherMethod();
}
Note that if you are dealing with threads, that Blocked condition is a major synchronization hazard.
If you really need to register for PropertyChanged from code, then your best bet is to just unregister with -=. That way the UI still gets its event, but you don't.

How to implement INotifyPropertyChanged without setter?

I need to implement INotifyPropertyChanged into my class (my goal is, to update a ListView every time an Item from 'JobDataGroup.Items' gets deleted), but in every tutorial, OnPropertyChanged gets called from the setter. Since I have no setter, how do I procede?
My Class:
public class JobDataGroup : repVReportsDataCommon, INotifyPropertyChanged
{
public ObservableCollection<ServiceJobItem> Items
{
get { return new ObservableCollection<ServiceJobItem>(repVReportsDataSource.GetJobItems().Where(_predicate)); }
}
#region PropertyChanged
public event PropertyChangedEventHandler PropertyChanged;
protected void OnPropertyChanged(string info)
{
PropertyChangedEventHandler handler = PropertyChanged;
if(handler != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(info));
}
}
#endregion
}
It doesn't matter from where you call your OnPropertyChanged method, call it when the property needs to be reevaluated.
Since you are recreating your collection every time the getter is accessed, there is no point in using an ObservableCollection.
You might as well just use a List instead and raise OnPropertyChanged manually:
public List<ServiceJobItem> Items { get; private set; }
void UpdateItems() {
Items = new List<ServiceJobItem>(repVReportsDataSource.GetJobItems().Where(_predicate));
OnPropertyChanged("Items");
}

Handling OnPropertyChanged

I'm not well versed in event-based programming. Basically, I'm still stumbling around with it. I'm trying to get something set up, but even with the tutorials, I can't wrap my head around it. What I would like to do (in words) is the following:
I have a dataobject where a property changes. I notice this in the setter of the property, and want to raise an event that the property has changed.
Elsewhere (in a different class entirely), I want to know that the property on this object has changed, and take some action.
Now I'm sure this is a common enough scenario, but my google-fu is letting me down. I'm simply not understanding http://msdn.microsoft.com/en-us/library/ms743695.aspx.
I have this:
public class ChattyClass {
private int someMember;
public event PropertyChangedEventHandler PropertyChanged;
public int SomeMember {
get {
return this.someMember;
}
set {
if (this.someMember != value){
someMember = value;
// Raise event/fire handlers. But how?
}
}
}
public class NosyClass{
private List<ChattyClass> myChatters;
public void addChatter(ChattyClass chatter){
myChatters.add(chatter);
// Start listening to property changed events
}
private void listner(){
// I want this to be called when the PropertyChangedEvent is called
Console.WriteLine("Hey! Hey! Listen! A property of a chatter in my list has changed!");
}
}
What do I do to wire this up?
Concerning the comment pointing me back to the link:
In the example I see:
protected void OnPropertyChanged(string name)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null)
{
handler(this, new PropertyChangedEventArgs(name));
}
}
What I'm not understanding:
Why isn't this just calling PropertyChanged(this, new PropertyCHangedEventArgs(name))
Where does PropertyChanged get assigned?
What does the assignment look like?
You have to fire the event. In the example on MSDN, they made a protected method OnPropertyChanged to handle this easier (and to avoid duplicate code).
// Create the OnPropertyChanged method to raise the event
protected void OnPropertyChanged(string name)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null)
{
handler(this, new PropertyChangedEventArgs(name));
}
}
What this method does, is look whether there is an event handler assigned or not (if it is not assigned and you just call it, you'll get a NullReferenceException). If there is one assigned, call this event handler. The event handler provided, has to have the signature of the PropertyChangedEventHandler delegate. This signature is:
void MyMethod(object sender, PropertyChangedEventArgs e)
Where the first parameter has to be of the type object and represents the object that fires the event, and the second parameter contains the arguments of this event. In this case, your own class fires the event and thus give this as parameter sender. The second parameter contains the name of the property that has changed.
Now to be able to react upon the firing of the event, you have to assign an event handler to the class. In this case, you'll have to assign this in your addChatter method. Apart from that, you'll have to first define your handler. In your NosyClass you'll have to add a method to do this, for example:
private void chatter_PropertyChanged(object sender, PropertyChangedEventArgs e)
{
Console.WriteLine("A property has changed: " + e.PropertyName);
}
As you can see, this method corresponds to the signature I explained before. In the second parameter, you'll be able to find the information of which parameter has been changed. Last thing to do, is add the event handler. Now in your addChatter method, you'll have to assign this:
public void AddChatter(ChattyClass chatter)
{
myChatters.Add(chatter);
// Assign the event handler
chatter.PropertyChanged += new PropertyChangedEventHandler(chatter_PropertyChanged);
}
I would suggest you to read something about events in .NET / C#: http://msdn.microsoft.com/en-us/library/awbftdfh . I think after reading/learning this, things will be more clear to you.
You can find a console application here on pastebin if you would like to test it quickly (just copy/paste into a new console application).
With newer versions of C#, you can inline the call to the event handler:
// inside your setter
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(MyProperty)));
You could also use something like Fody PropertyChanged to automatically generated the necessary code (visit the link to their GitHub page, with samples).
The link that you looked is for the MVVM pattern and WPF. It is not a general C# implementation. You need something like this:
public event EventHandler PropertyChanged;
public int SomeMember {
get {
return this.someMember;
}
set {
if (this.someMember != value) {
someMember = value;
if (PropertyChanged != null) { // If someone subscribed to the event
PropertyChanged(this, EventArgs.Empty); // Raise the event
}
}
}
...
public void addChatter(ChattyClass chatter) {
myChatters.add(chatter);
chatter.PropertyChanged += listner; // Subscribe to the event
}
// This will be called on property changed
private void listner(object sender, EventArgs e){
Console.WriteLine("Hey! Hey! Listen! A property of a chatter in my list has changed!");
}
If you want to know what property has changed you need to change your event definition to:
public event PropertyChangedEventHandler PropertyChanged;
And change the calling to:
public int SomeMember {
get {
return this.someMember;
}
set {
if (this.someMember != value){
someMember = value;
if (PropertyChanged != null) { // If someone subscribed to the event
PropertyChanged(this, new PropertyChangedEventArgs("SomeMember")); // Raise the event
}
}
}
private void listner(object sender, PropertyChangedEventArgs e) {
string propertyName = e.PropertyName;
Console.WriteLine(String.Format("Hey! Hey! Listen! a {0} of a chatter in my list has changed!", propertyName));
}
why isn't this just calling PropertyChanged(this, new
PropertyCHangedEventArgs(name))
Because if no one attached an handler to the event, then the PropertyChanged object returns null. So you'll have to ensure it's not null before calling it.
where does PropertyChanged get assigned?
In the "listener" classes.
For example, you could write in other class:
ChattyClass tmp = new ChattyClass();
tmp.PropertyChanged += (sender, e) =>
{
Console.WriteLine(string.Format("Property {0} has been updated", e.PropertyName));
};
What does the assignment look like?
In C# we use the assignment operators += and -= for events. I recommend reading the following article to understand how to write event handlers using the anonymous method form (example above) and the "old" form.
From taking the original code, and incorporating #Styxxy 's answer, I come out with:
public class ChattyClass : INotifyPropertyChanged
{
private int someMember, otherMember;
public int SomeMember
{
get
{
return this.someMember;
}
set
{
if (this.someMember != value)
{
someMember = value;
OnPropertyChanged("Some Member");
}
}
}
public int OtherMember
{
get
{
return this.otherMember;
}
set
{
if (this.otherMember != value)
{
otherMember = value;
OnPropertyChanged("Other Member");
}
}
}
protected virtual void OnPropertyChanged(string propertyName)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null) handler(this, new PropertyChangedEventArgs(propertyName));
}
public event PropertyChangedEventHandler PropertyChanged;
}
public class NosyClass
{
private List<ChattyClass> myChatters = new List<ChattyClass>();
public void AddChatter(ChattyClass chatter)
{
myChatters.Add(chatter);
chatter.PropertyChanged+=chatter_PropertyChanged;
}
private void chatter_PropertyChanged(object sender, PropertyChangedEventArgs e)
{
Console.WriteLine("A property has changed: " + e.PropertyName);
}
}

Bound UserControl is not updating data source

I have a UserControl that has a Textbox, Button, and a Tooltip controls on it. It does implement INotifyPropertyChanged I have tried overriding the Text property and adding my own property, but in all cases the control reads from the bound data source fine, but never updates the data source. My events are raised when the text is changed. Some of the code is below. All other standard controls are working fine. What do I need to get the control to update the data source when the user has entered or changed the value?
public partial class UrlControl : UserControl, INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
[Bindable(true)]
[Browsable(true)]
public string Url
{
get
{
return url.Text;
}
set
{
if (value != url.Text)
{
url.Text = value;
OnPropertyChanged("Url");
}
}
}
protected virtual void OnPropertyChanged(string propertyName)
{
OnPropertyChanged(new PropertyChangedEventArgs(propertyName));
}
protected virtual void OnPropertyChanged(PropertyChangedEventArgs e)
{
if (PropertyChanged != null)
{
PropertyChanged(this, e);
}
}
This is the binding code from the form designer.
this.urlControl1.DataBindings.Add(new System.Windows.Forms.Binding("Url", this.customerBindingSource, "First", true, System.Windows.Forms.DataSourceUpdateMode.OnPropertyChanged));
}
INotifyPropertyChanged is for datasources. It allows your datasource to notify bound controls and other listeners of property changes. However, controls themselves use a different mechanism. It's a bit strange: you create events on your control with the naming convention <PropertyName>Changed. When the value of a property changes, you raise the associated event.
Example:
public string Url
{
get { return url.Text; }
set
{
if (value != url.Text)
{
url.Text = value;
OnUrlChanged(); // raise event
}
}
}
public event EventHandler UrlChanged;
private void OnUrlChanged()
{
// raise the UrlChanged event
if (UrlChanged != null)
UrlChanged(this, new EventArgs());
}
That's all you need to do. The Databinding Fairies will see that event and hook it up when you create the binding.
Here's the topic on MSDN: How to: Apply the PropertyNameChanged Pattern
This should work well for reading values from the datasource.
However, when it comes to writing values to the datasource it looks like you're storing and getting the Url value directly from the url textbox. However, you're not raising property change notifications when the textbox's text is changed within the UI. To fix this, add a TextChanged event handler on the textbox, which can simple call:
void url_TextChanged(object sender, EventArgs e)
{
OnPropertyChanged("Url");
OnUrlChanged(); // See additional note below
}
As a side, although implementing INotifyPropertyChanged should work... When it comes to Windows Forms binding you can also create an event with the property name suffixed with "Changed" and the binding should watch that:
public event EventHandler UrlChanged;
protected virtual void OnUrlChanged()
{
var handler = UrlChanged;
if (handler != null)
{
handler(this, EventArgs.Empty);
}
}
[Bindable(true)]
[Browsable(true)]
public string Url
{
get
{
return url.Text;
}
set
{
if (value != url.Text)
{
url.Text = value;
OnPropertyChanged("Url");
OnUrlChanged();
}
}
}

Categories

Resources