[英]How do you reference a viewmodel from a CustomControl using MVVM light
I'm used to setting the datacontext of a UserControl in xaml to a viewmodel using the MVVM-light locator. 我习惯使用MVVM-light定位器将xaml中UserControl的datacontext设置为viewmodel。 eg: 例如:
DataContext="{Binding SplashMainViewModel, Mode=OneWay, Source={StaticResource Locator}}"
This is done in the view's markup in xaml. 这是在xaml中的视图标记中完成的。
How does one go about setting the datacontext of a CustomControl to a viewmodel? 如何将CustomControl的datacontext设置为viewmodel? In VS the custom control is created with the following: 在VS中,使用以下命令创建自定义控件:
public class CustomControl1 : Control
{
static CustomControl1()
{
DefaultStyleKeyProperty.OverrideMetadata(typeof(CustomControl1),new FrameworkPropertyMetadata(typeof(CustomControl1)));
}
}
But it doesn't have the usual xaml markup. 但它没有通常的xaml标记。
Try something like: 尝试类似的东西:
public class CustomControl1 : Control
{
static CustomControl1()
{
DefaultStyleKeyProperty.OverrideMetadata(typeof(CustomControl1),new FrameworkPropertyMetadata(typeof(CustomControl1)));
}
public override void OnApplyTemplate()
{
base.OnApplyTemplate();
DataContext = ((MyLocatorType)Resources["Locator"]).SplashMainViewModel;
}
}
... or set it in the XAML of the template ( Themes\\Generic.xaml
). ...或将其设置在模板的XAML中( Themes\\Generic.xaml
)。
Rico Suter's demonstrates how to set CustomControl1's DataContext for all instances of CustomControl1. Rico Suter演示了如何为CustomControl1的所有实例设置CustomControl1的DataContext。 I'm guessing this is what you want to do. 我猜这就是你想要做的。
You could use your normal approach to set the DataContext on a specific instance of CustomControl1 (in the xaml where it is declared). 您可以使用常规方法在CustomControl1的特定实例上设置DataContext(在声明它的xaml中)。 I'm guessing this is not what you want to do but I'm including for completeness. 我猜这不是你想要做的,但我包括完整性。 If there is only one instance of CustomControl1 this may be more convenient. 如果只有一个CustomControl1实例,这可能更方便。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.