【发布时间】:2017-09-07 22:59:14
【问题描述】:
我在 SliderViewModel 中有依赖属性,其中此视图模型实现 DependencyObject 并设置为 BRSliderUserControl 的数据上下文。如何从 AmplitudeOptionsUserControl 绑定到视图模型中的依赖属性。有没有可能这样做。我的猜测是我需要在 BRSliderUserControl 中创建另一个依赖属性,然后将更新值发送到视图模型。这是正确的方法吗?
SliderViewModel.cs
public Class SliderViewModel:DependencyObject
{
public AnalysisViewType AnalysisTypeValue
{
get { return (AnalysisViewType)GetValue(AnalysisTypeDependencyProperty); }
set { SetValue(AnalysisTypeDependencyProperty, value); }
}
public static readonly DependencyProperty AnalysisTypeDependencyProperty =
DependencyProperty.Register("AnalysisTypeValue", typeof(AnalysisViewType), typeof(SliderViewModel),
new PropertyMetadata(AnalysisViewType.Unassigned, OnAnalysisTypeChanged));
private static void OnAnalysisTypeChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
//Do something here
}
}
BRSliderUserControl.xaml.cs
public BRSliderUserControl()
{
InitializeComponent();
SliderViewModel sliderViewModel = new SliderViewModel();
this.DataContext = sliderViewModel;
}
现在如何从另一个用户控件绑定到该依赖项属性?
AmplitudeOptionsControl.xaml
//This does not work..
<lib:BRSliderUserControl
Grid.Row="5"
Grid.Column="0"
Grid.ColumnSpan="3"
AnalysisTypeValue="{Binding AmplitudeOptionsVM.AnalysisType,RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type UserControl}}}"
/>
【问题讨论】:
-
您的视图模型不应该是依赖对象,也不需要它们。改用 INotifyPropertyChanged,它更轻量级,更合适。
-
什么是
AmplitudeOptionsVM?AmplitudeOptionsControl的属性名称? -
AmplitudeOptionsVM 是类名,AnalysisType 是类内的属性名。
-
嗯,属性的类型不是属性的名称。如果你想要一个字符串的长度,你不说
"foo".int,你说"foo".Length。AmplitudeOptionsControl是否拥有该虚拟机的副本?如果是DataContext,你要AnalysisTypeValue="{Binding DataContext.AnalysisType,RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type UserControl}}}"
标签: wpf mvvm dependency-properties