Reputation: 15
I'm new to WPF Data binding and can't figure it how to update the property from my viewmodel
I have a class named Patient
public string FirstName { get; set; } = "";
public string MiddleName { get; set; } = "";
public string LastName { get; set; } = "";
updates to the patient class is working
private Data.Patient patient;
public Data.Patient Patient
{
get { return patient; }
set
{
patient = value;
NotifyPropertyChanged("Patient");
}
}
a property on my viewmodel which is not updated by the patient class
public string FullName
{
get { return Patient.LastName + " " + Patient.FirstName + " " + Patient.MiddleName; }
}
I'm trying to update the TextBlock Text property
<TextBlock Text="{Binding FullName}" FontSize="14.667" />
how to apply the updates from the Class to my FullName property? Updates are applied when I rerun the application.
Many Thanks
Upvotes: 1
Views: 631
Reputation: 12449
Your problem is you're not notifying UI that Fullname
property has changed. Technically it has not changed, but it is dependent on some other property.
The simplest solution here is to raise NotifyProperty event for all properties. You won't have to write plenty of code for it, just pass null
in NotifyPropertyChanged();
private Data.Patient patient;
public Data.Patient Patient
{
get { return patient; }
set
{
patient = value;
NotifyPropertyChanged(null); //informs view that all properties updated
}
}
It will tell your model that all properties have been updated.
The PropertyChanged event can indicate all properties on the object have changed by using either null or String.Empty as the property name in the PropertyChangedEventArgs.
Upvotes: 1
Reputation: 15
I can't seem to make it work. I added the property to my class so any changes to the class will be notify the UI, still it's not working the way I want. But I found a solution.
<TextBlock FontSize="14.667">
<TextBlock.Text>
<MultiBinding StringFormat=" {0} {1} {2}">
<Binding Path="Patient.LastName" />
<Binding Path="Patient.FirstName"/>
<Binding Path="Patient.MiddleName"/>
</MultiBinding>
</TextBlock.Text>
</TextBlock>
Thanks for the help.
Upvotes: 0
Reputation: 1923
Like the Patient
property with the NotifyPropertyChanged(...)
, you have to inform the, when the property Fullname has changed. To do that, call NotifyPropertyChanged("FullName")
in the setters of the three properties: FirstName, MiddleName and LastName.
Also consider, that NotifyPropertyChanged could be null and use therefore:
if (NotifyPropertyChanged != null)
NotifyPropertyChanged("FullName");
Upvotes: 0
Reputation: 5133
Change your binding from Text="{Binding FullName}"
to Text="{Binding FullName, Mode="OneWay", UpdateSourceTrigger="PropertyChanged"}"
that should trigger the PropertyChanged-Event.
Upvotes: 0