C
C#3mo ago
intee_

✅ Invoking an event on property changed (WPF)

Hey all, Just wondering if someone can help me wrap my head around how this works, I am not sure where I am getting caught up but I am sure I am not understanding something. Just started learning WPF and C#. Sorry for the data dump. I have a text box, a button and a textblock. I am just trying to make the text from the text box be set in the textblock. I have have my bindings working but I don't understand HOW they are working. I have a PropertyChangedEventHandler in my main window code behind and I have the public and private properties for the binding as well. In the setter of the binding I am calling PropertyChanged?.Invoke(this, new PropertyChangedEventArgs("DisplayText")); This is where I am getting confused I think. When a property is changed on the UI the properties setter is called by that event handler (Handled by INotifyPropertyChanged) (???) How exactly does this part of it work? I'm not using any relay commands or anything like that, just straight data binding from the UI to the code behind. Hope this makes at least a little sense...
8 Replies
intee_
intee_OP3mo ago
// Inside the MainWindow Constructor I am setting the data context:
DataContext = this;
//

private string displayText;

public event PropertyChangedEventHandler? PropertyChanged;

public string DisplayText {
get { return displayText; }
set {
displayText = value;
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs("DisplayText"));
}
}
// Inside the MainWindow Constructor I am setting the data context:
DataContext = this;
//

private string displayText;

public event PropertyChangedEventHandler? PropertyChanged;

public string DisplayText {
get { return displayText; }
set {
displayText = value;
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs("DisplayText"));
}
}
Angius
Angius3mo ago
Not sure what do you mean by "how does this part work". When a property is set, it's setter is called
intee_
intee_OP3mo ago
I'm just confused as to how the UI called the setter, I think. I've got analysis paralysis at the moment sorry haha. So as long as I have the properties in the viewmodel / whatever data context the view is using and the bindings in the xaml with the same name as the public property, INotify just does everything for us?
Angius
Angius3mo ago
Basically
intee_
intee_OP3mo ago
And will that be the same for every property on any model? Just for the PropertyChanged that is. Thanks heaps mate, think I am just over thinking it too much!
Angius
Angius3mo ago
Yeah, all properties that need to be watched for changes are handled this way There's even a source generator to just generate the whole boilerplate for you
intee_
intee_OP3mo ago
I was looking at the MVVM toolkit before but figure I should understand what it actually does first haha
Angius
Angius3mo ago
Yep, that's the one
Want results from more Discord servers?
Add your server