I want to expose a property that is a string format of two other dependency properties. How do I make this work so anything bound to the derived property is also updated when the true dependency property is updated?
public static readonly DependencyProperty DeviceProperty =
DependencyProperty.Register("Device", typeof(string), typeof(SlaveViewModel));
public static readonly DependencyProperty ChannelProperty =
DependencyProperty.Register("Channel", typeof(Channels), typeof(SlaveViewModel));
public string Device
{
get { return (string)GetValue(DeviceProperty); }
set { SetValue(DeviceProperty, value); }
}
public Channels Channel
{
get { return (Channels)GetValue(ChannelProperty); }
set { SetValue(ChannelProperty, value); }
}
Now I would like to be able to bind to the following derived property and have it treated as a dependency property:
public string DeviceDisplay
{
get
{
return string.Format("{0} (Ch #{1})", Device, (int)Channel);
}
}
I'm able to do this by adding callbacks. It works well but it seems a bit verbose. Is there an easier way to do this other than the following?
public static readonly DependencyProperty DeviceProperty =
DependencyProperty.Register("Device", typeof(string), typeof(SlaveViewModel),
new FrameworkPropertyMetadata("", FrameworkPropertyMetadataOptions.None,
new PropertyChangedCallback(OnDevicePropertyChanged)));
private static void OnDevicePropertyChanged(DependencyObject sender, DependencyPropertyChangedEventArgs args)
{
SlaveViewModel model = (SlaveViewModel)sender;
model.DeviceDisplay = string.Format(string.Format("{0} (Ch #{1})",
args.NewValue, (int)model.Channel));
}
public static readonly DependencyProperty ChannelProperty =
DependencyProperty.Register("Channel", typeof(Channels), typeof(SlaveViewModel),
new FrameworkPropertyMetadata(Channels.Channel1, FrameworkPropertyMetadataOptions.None,
new PropertyChangedCallback(OnChannelPropertyChanged)));
private static void OnChannelPropertyChanged(DependencyObject sender, DependencyPropertyChangedEventArgs args)
{
SlaveViewModel model = (SlaveViewModel)sender;
model.DeviceDisplay = string.Format(string.Format("{0} (Ch #{1})",
model.Device, (int)args.NewValue));
}
public static readonly DependencyPropertyKey DeviceDisplayPropertyKey =
DependencyProperty.RegisterReadOnly("DeviceDisplay", typeof(string),
typeof(SlaveViewModel), new FrameworkPropertyMetadata(""));
public static readonly DependencyProperty DeviceDisplayProperty =
DeviceDisplayPropertyKey.DependencyProperty;
public string DeviceDisplay
{
get { return (string)GetValue(DeviceDisplayProperty); }
protected set { SetValue(DeviceDisplayPropertyKey, value); }
}