Reputation: 75
I have a User Control(next UC) with label. I need on button click change a UC label content. On UC codebehind i create DependencyProperty and methods to change a label.
public string InfoLabel
{
get
{
return (string)this.GetValue(InfoLabelProperty);
}
set
{
this.SetValue(InfoLabelProperty, value);
}
}
private static void InfoLabelChangeCallback(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
UserControl1 uc = d as UserControl1;
uc.CInfoLabel.Content = uc.InfoLabel;
}
public static readonly DependencyProperty InfoLabelProperty = DependencyProperty.Register("InfoLabel", typeof(string), typeof(UserControl1), new PropertyMetadata("", new PropertyChangedCallback(InfoLabelChangeCallback)));
On ShellView i got Binding on control and button.
<c:UserControl1 InfoLabel="{Binding InfoLabel1}" />
<Button x:Name="ChangeUserControllButton"/>
On ShellViewModel I have Binding InfoLabel1.
private string infoLabel= "something";
public string InfoLabel1
{
get
{
return infoLabel;
}
set
{
infoLabel = value;
}
}
public void ChangeUserControllButton()
{
InfoLabel1 = "Hello world";
}
The problem is When a UC is initialize, then it`s work. I mean label from UC will have content "something", but when I Click on button, content not changing to "Hello world". How to make it right?
Upvotes: 0
Views: 928
Reputation: 247018
View model needs to implement INotifyPropertyChanged
so as to be able to notify UI that it should refresh/update because the bound model has changed. I believe that there is already a base class that provides that functionality.
Reference Caliburn.Micro.PropertyChangedBase
Update ShellViewModel
to be derived from PropertyChangedBase
and then in property call one of the available methods that would allow your view model to notify UI of property changed.
public class ShellViewModel : PropertyChangedBase {
private string infoLabel= "something";
public string InfoLabel1 {
get {
return infoLabel;
}
set {
infoLabel = value;
NotifyOfPropertyChange();
//Or
//Set(ref infoLabel, value);
}
}
public void ChangeUserControllButton() {
InfoLabel1 = "Hello world";
}
}
Read more at https://caliburnmicro.com/ to get examples of how to use the framework.
Upvotes: 2