【问题标题】:Put ViewModel in the right place将 ViewModel 放在正确的位置
【发布时间】:2017-07-29 12:10:05
【问题描述】:

我有一个 Silverlight 项目。在 App.xaml 中,我们有

<Application.Resources>
    <ResourceDictionary>
        <ResourceDictionary.MergedDictionaries>
            <ResourceDictionary Source="Assets/Styles.xaml"/>
        </ResourceDictionary.MergedDictionaries>
    </ResourceDictionary>
</Application.Resources>

然后在Assets/Styles.xaml 中,我们有 ViewModel。

<ResourceDictionary
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:data="clr-namespace:System.Windows.Controls;assembly=System.Windows.Controls.Data"
xmlns:local="clr-namespace:MyWeb.MyProj"
xmlns:sys="clr-namespace:System;assembly=mscorlib"
xmlns:localViewModels="clr-namespace:MyWeb.MyProj.ViewModels">

<ResourceDictionary.MergedDictionaries>

</ResourceDictionary.MergedDictionaries>

<localViewModels:MyProjViewModel x:Key="ViewModel" />
...
<telerikGridView:RadGridView
    ...
    ItemsSource="{Binding Schedules}"
    SelectedItem="{Binding SelectedWeek, Mode=TwoWay, Source={StaticResource ViewModel}}">

最后在 MainPage.xaml.cs 中,我们有

private MyProjViewModel viewModel;

public MyProjViewModel ViewModel
{
    get
    {
        if (this.viewModel == null)
        {
            this.viewModel = new MyProjViewModel();
        }
        return this.viewModel;
    }
    set
    {
        if (this.viewModel != value)
        {
            this.viewModel = value;
        }
    }
}

然后在构造函数中,我们使用 ViewModel 作为

public MainPage()
{
    InitializeComponent();
    this.DataContext = this.ViewModel;
    this.ViewModel = this.DataContext as MyProj;
}

虽然它有效,但我不确定它是否是使用 ViewModel 的最佳结构,因为它位于 Styles.xaml 中。如果不是,如何纠正?

【问题讨论】:

  • 我会从 Styles 中删除 ViewModel 定义。把它放在 MainPage 构造函数中。

标签: .net xaml silverlight mvvm


【解决方案1】:

如果您希望 ViewModel 的一个特定实例可用于应用程序的整个生命周期,您可以在资源字典中定义它,就像您所做的那样(当然您必须从资源字典中引用它,并且不要像你在问题中那样使用)。

更好的解决方案是在视图的构造函数中创建它(没有styles.xaml中的定义)。

public MyProjectViewModel ViewModel { get; set; }

public MainPage()
{
     InitializeComponent();
     this.ViewModel = new MyProjViewModel();
     this.DataContext = this.ViewModel;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-09-23
    • 1970-01-01
    • 2014-09-26
    • 2019-07-13
    • 2014-03-10
    • 2021-06-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多