I have a class with some properties. This class inherit from BindableBase (Prism) for notify properties changes. And another viemodel class that inherit also from BindableBase and has a property of the first class. I have a usercontrol that bind to this properties. This control works well, but when I change one property of the first class, this doesn't propagate the changes to the property of the viewmodel class. Is there a way to make that when I change one property, this fire the property change event in the property of viewmodel class. Thanks.
using Prism.Mvvm;
using System.Windows.Media;
// I use this class to bind with the user control
public class FontSetting : BindableBase
{
private FontFamily fontFamily;
public FontFamily FontFamily
{
get => fontFamily;
set => SetProperty(ref fontFamily, value);
}
private int fontSize;
public int FontSize
{
get => fontSize;
set => SetProperty(ref fontSize, value);
}
private Color textColor = Colors.Black;
public Color TextColor
{
get => textColor;
set => SetProperty(ref textColor, value);
}
}
// This class is binding to the window
public class ViewModel : BindableBase
{
// This property is binding to the user control
private FontSetting fontSetting = new FontSetting();
public FontSetting FontSetting
{
get => fontSetting;
set
{
var oldValue = fontSetting;
SetProperty(ref fontSetting, value);
if (oldValue != value)
{
// When I change, for example the FontSize, this doesn't work.
// But if I check FontSetting.FontSize, this property has changed.
ChangeProperty(nameof(FontSetting));
}
}
}
...
private void ChangeProperty(string propertyName)
{
switch (propertyName)
{
case "Text":
textBlock.Text = Text;
break;
case "FontSetting":
textBlock.FontFamily = FontSetting.FontFamily;
textBlock.FontSize = FontSetting.FontSize;
textBlock.Foreground = new SolidColorBrush(FontSetting.TextColor);
break;
case "BackgroundColor":
textBlock.Background = new SolidColorBrush(BackgroundColor);
break;
}
}
}
Update: Solution thanks to Clemens:
private FontSetting fontSetting;
public FontSetting FontSetting
{
get => fontSetting;
set
{
if (fontSetting != value)
{
if (fontSetting != null)
{
// Clean event handler
fontSetting.PropertyChanged -= FontSettingChanged;
}
fontSetting = value;
if (fontSetting != null)
{
// Set event handler
fontSetting.PropertyChanged += FontSettingChanged;
}
RaisePropertyChanged(nameof(FontSetting));
}
}
}
private void FontSettingChanged(object sender, PropertyChangedEventArgs args)
{
ChangeProperty(nameof(FontSetting));
RaisePropertyChanged(nameof(FontSetting));
}