2
我想公開一個屬性是兩個其他依賴項屬性的字符串格式。我如何使這項工作,所以綁定到派生屬性的任何東西也會在更新真正的依賴項屬性時更新?是否可以使用WPF派生的依賴項屬性?
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); }
}
好一點,所以我想我的視圖模型應該只使用INotifyPropertyChanged的呢? DP屬性更適合wpf usercontrols上的屬性嗎? – 2012-08-09 02:09:35
@JasonButera:是的,是的。 – 2012-08-09 02:11:00