WPF派生的依赖属性是否可能?

时间:2012-08-09 01:52:38

标签: wpf dependency-properties readonly

我想公开一个属性,它是另外两个依赖属性的字符串格式。我如何使这项工作,以便在更新真正的依赖项属性时更新绑定到派生属性的任何内容?

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

现在我希望能够绑定到以下派生属性并将其视为依赖属性:

public string DeviceDisplay
{
    get 
    {
        return string.Format("{0} (Ch #{1})", Device, (int)Channel);
    }
}

我可以通过添加回调来做到这一点。它运作良好,但似乎有点冗长。除了以下内容之外,还有更简单的方法吗?

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

1 个答案:

答案 0 :(得分:0)

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

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