[英]Can I set my user control datacontext in xaml via a dependency property bound to a property on the parent control in wpf?
I have a user control with a dependency property called ViewModel. 我有一个用户控件,其依赖项名为ViewModel。 I want the value that this property is set to to be the data context for this control.
我希望将此属性设置为该控件的数据上下文的值。
Here is an example of its usage; 这是一个用法示例。
<uc:MyCustomControl ViewModel="{Binding CustomControlViewModel}"/>
Here is the code-behind for the ViewModel dependency property for "MyCustomControl" 这是“ MyCustomControl”的ViewModel依赖项属性的代码隐藏
public static readonly DependencyProperty ViewModelProperty = DependencyProperty.Register(
"ViewModel", typeof(CustomControlViewModel), typeof(MyCustomControl), new PropertyMetadata(default(CustomControlViewModel), PropertyChangedCallback));
public CustomControlViewModel ViewModel
{
get { return (CustomControlViewModel)GetValue(ViewModelProperty); }
set
{
SetValue(ViewModelProperty, value);
}
}
private static void PropertyChangedCallback(DependencyObject dependencyObject, DependencyPropertyChangedEventArgs dependencyPropertyChangedEventArgs)
{
var control = (MyCustomControl) dependencyObject;
if (control == null)
{
return;
}
control.DataContext = (CustomControlViewModel) dependencyPropertyChangedEventArgs.NewValue;
}
This is the constructor for the "MyCustomControl"; 这是“ MyCustomControl”的构造函数;
public MyCustomControl()
{
InitializeComponent();
}
This doesn't seem to work, what might I be doing wrong? 这似乎不起作用,我可能做错了什么?
DataContext
itself is a DependencyProperty
. DataContext
本身是一个DependencyProperty
。 You can directly assign it with your viewmodel like this. 您可以像这样直接用您的viewmodel分配它。
<uc:MyCustomControl DataContext="{Binding CustomControlViewModel}"/>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.