【问题标题】:How do you reference a viewmodel from a CustomControl using MVVM light如何使用 MVVM 灯光从 CustomControl 引用视图模型
【发布时间】:2015-02-25 09:34:40
【问题描述】:

我习惯于使用 MVVM-light 定位器将 xaml 中的 UserControl 的数据上下文设置为视图模型。例如:

DataContext="{Binding SplashMainViewModel, Mode=OneWay, Source={StaticResource Locator}}"

这是在 xaml 中的视图标记中完成的。

如何将 CustomControl 的数据上下文设置为视图模型?在 VS 中,自定义控件是使用以下内容创建的:

    public class CustomControl1 : Control
    {
        static CustomControl1()
        {
            DefaultStyleKeyProperty.OverrideMetadata(typeof(CustomControl1),new FrameworkPropertyMetadata(typeof(CustomControl1)));
        }
    }

但它没有通常的 xaml 标记。

【问题讨论】:

  • 你能把你的问题说清楚吗?要将CustomViewModel 设置为CustomControl?
  • 自定义控件通常在Themes\Generic.xaml 中有一个样式。您也许可以在那里设置 DataContext (假设 Locator 资源在那里可用)。否则,您应该能够在控件的构造函数中设置它。或者只是不要全部设置,让其在控件实例化时被继承或显式设置。

标签: c# wpf mvvm-light


【解决方案1】:

尝试类似:

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

... 或在模板的 XAML 中设置 (Themes\Generic.xaml)。

【讨论】:

    【解决方案2】:

    Rico Suter 演示了如何为 CustomControl1 的所有实例设置 CustomControl1 的 DataContext。我猜这就是你想要做的。

    您可以使用常规方法在 CustomControl1 的特定实例上设置 DataContext(在声明它的 xaml 中)。我猜这不是您想要做的,但为了完整性,我将其包括在内。如果只有一个 CustomControl1 实例,这可能更方便。

    【讨论】:

    • 我可能会在 itemsControl 数据模板中重复此控件 - 所以我需要将特定实例绑定到控件到它自己的视图模型。
    猜你喜欢
    • 2018-11-25
    • 2015-05-13
    • 2012-07-22
    • 1970-01-01
    • 2017-10-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-10-03
    相关资源
    最近更新 更多