2

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); }
}
4

1 回答 1

0

我看到复制粘贴的代码,您可以将两个回调都指向一个方法。不知道是否有更简单的方法,但我对此表示怀疑。

(也typeof(SlaveViewModel)暗示这是 VM 代码:由于线程关联,我永远不会在 VM 中使用 DP。)

于 2012-08-09T01:55:34.717 回答