【问题标题】:MVVMLight - how to get a reference to the ViewModel in the View?MVVMLight - 如何在视图中获取对 ViewModel 的引用?
【发布时间】:2012-04-05 01:54:59
【问题描述】:

我正在构建一个 Windows Phone 7 应用程序,我需要在我的视图中引用我的 ViewModel,以便我可以从我的事件处理程序中设置一个属性。唯一的问题是我无法获得该参考。

我做了什么;

我有一个 ViewModelLocator(删除了不相关的位):

static ViewModelLocator()
{
    ServiceLocator.SetLocatorProvider(() => SimpleIoc.Default);

    SimpleIoc.Default.Register<TunerViewModel>();
}

[SuppressMessage("Microsoft.Performance", "CA1822:MarkMembersAsStatic", Justification = "This non-static member is needed for data binding purposes.")]
public TunerViewModel Tuner
{
    get { return ServiceLocator.Current.GetInstance<TunerViewModel>(); }
}

还有一个视图(XAML):

DataContext="{Binding Tuner, Source={StaticResource Locator}}">

以及视图的代码隐藏:

public partial class Tuner : PhoneApplicationPage
{
    private readonly TunerViewModel _viewModel;

    public Tuner()
    {
        _viewModel = DataContext as TunerViewModel;

        InitializeComponent();
    }

我找到了这个链接MVVM View reference to ViewModel,其中 DataContext 被转换为 ViewModel,所以我尝试了同样的方法,因为它看起来是一个很好的解决方案。但是,演员表后我的 _viewModel 字段为空。为什么会这样,我该如何解决?我在 Google/Stackoverflow 上找不到它

提前致谢:)

【问题讨论】:

  • 您是否在 App.xaml 资源中设置了定位器(或者,在您的页面资源中,但不是 DRY)?因为这看起来好像没有在您的 XAML 绑定中找到视图模型。

标签: silverlight windows-phone-7 mvvm mvvm-light


【解决方案1】:

因为您在视图的构造函数中使用绑定表达式从 XAML 中设置了 DataContext,所以尚未设置 DataContext。这就是你得到 null 的原因。

Loaded 事件中或之后尝试转换DataContext

public Tuner()
{
    InitializeComponent();
    Loaded += OnTunerLoaded;
}

private void OnTunerLoaded(object sender, RoutedEventArgs routedEventArgs)
{
    _viewModel = DataContext as TunerViewModel;
}

【讨论】:

  • 准确来说,关键是在InitializeComponent被调用后获取VM,因为这里是解析XAML的地方,也是按需创建VM的地方。所以,严格来说,你不需要 Loaded 事件,你只需要在 InitializeComponent 返回后设置你的 _viewModel 属性:)
  • @LBugnion 是 WP7 中的行为改变了吗?因为在 WPF 中,如果我在 XAML 中设置 DataContext,即使在 InitializeComponent() 调用之后,用户控件的构造函数中也是 null...
  • 这不是我观察到的。如果我做 File、New Project、WPF4 MVVM Light 项目,并在 InitializeComponent 之后放置一个断点,DataContext 不为空,它已设置。你还观察到别的什么吗?
  • @LBugnion 是的,我知道有什么不同。我用这样的“子视图”测试了DataContext&lt;StackPanel&gt; &lt;WPF:TestView DataContext="{Binding ..." /&gt;...,然后 DataContext 将在 TestView 的构造函数中保持为空。但是,如果我在 TestView.xaml &lt;UserControl x:Class="WPF.TestView" DataContext="..." /&gt; 中设置 DataContext mvvm light way 那么在 InitializeComponent 之后它真的不为空。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-27
  • 2013-04-02
  • 2015-08-20
  • 2015-05-29
  • 1970-01-01
相关资源
最近更新 更多