【问题标题】:I can not get MVVM to work我无法让 MVVM 工作
【发布时间】:2015-06-18 19:47:34
【问题描述】:

我正在拼命尝试实现 MVVM,但由于某种原因它无法正常工作。我在 Windows 8.1 Store App 上使用 MVVM light。

我做错了什么?到目前为止,我遵循了三个教程,但似乎没有任何效果..

我从 Web 服务中检索数据,这部分 100% 工作得很好。 ObservableCollection 包含数据。

我的其余代码如下所示:

ViewModelLocator:

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

    if (ViewModelBase.IsInDesignModeStatic)
    {
        // Create design time view services and models
        SimpleIoc.Default.Register<IDesignTimeWeatherServiceLayer, DesignTimeWeatherServiceLayer>();
    }
    else
    {
        // Create run time view services and models
        SimpleIoc.Default.Register<IWeatherServiceLayer, WeatherServiceLayer>();
    }

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


public WeatherViewModel Weather
{
    get
    {
        return ServiceLocator.Current.GetInstance<WeatherViewModel>();
    }
}

视图模型:

public class WeatherViewModel : ViewModelBase
{
    WeatherServiceLayer serviceLayer = new WeatherServiceLayer();

    public async void GetAllWeatherData()
    {
        WeatherData = await serviceLayer.GetAllWeatherAsync();
    }

    private ObservableCollection<Weather> weatherData;
    public ObservableCollection<Weather> WeatherData { get { return weatherData; } set { weatherData = value; RaisePropertyChanged("WeatherData"); } }
}

代码背后:

public MainPage()
{
    this.InitializeComponent();
    WeatherViewModel vm = new WeatherViewModel();
    vm.GetAllWeatherData();
}

查看:

...
DataContext="{Binding Weather, Source={StaticResource Locator}}">

<Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
    <GridView ItemTemplate="{StaticResource WeatherItemTemplate}" ItemsSource="{Binding Weather.WeatherData, Source={StaticResource Locator}}"/>
</Grid>

数据模板:

<DataTemplate x:Key="WeatherItemTemplate">
    <StackPanel>
        <TextBlock Text="{Binding Temperature}" Height="60" Margin="15,0,15,0"/>
        <TextBlock Text="{Binding WeekDay}" Margin="15,0,15,10"/>
    </StackPanel>
</DataTemplate>

【问题讨论】:

  • 虽然您已经提供了很多关于您正在做什么的详细信息,但它可以通过更好地描述“它不工作”的含义来帮助您获得答案。当您运行应用程序时实际发生了什么与您预期会发生什么?
  • 这不是您使用 MVVM Light 设置数据上下文的方式。要么使用视图模型定位器(需要将其设置为资源),要么在后面的代码中创建视图模型并在那里分配数据上下文。
  • 感谢您的反馈。当我启动应用程序时,我希望数据显示在我的 GridView 中。相反,我什么也没看到。
  • 你后面的代码没有意义。如果您使用 viewmodellocator,则应在 app.xaml 中将其设置为应用程序数据源,然后将数据上下文设置为天气属性。尝试在你的类构造函数中设置一些断点,看看调用了什么。
  • 小心在您的构造函数和设计时视图中访问数据 - 它会在不断重建时大大减慢您的设计器。

标签: c# mvvm winrt-xaml mvvm-light


【解决方案1】:

我不确定,但有几件事对我来说似乎是可疑的。最初,您设置 DataContext 属性。您确定您的 DataContext 是您在完成此任务后所期望的吗?调用 InitializeComponent 进行检查后,可以在视图的构造函数中设置断点。

在您的 ItemsSource 绑定中,您说的是定位器来源的“Weather.WeatherData”。这似乎是多余的,也许是错误的。也许只是尝试“WeatherData”并删除源规范。如果您的 DataContext 是 Weather,那么它将是用于该 xaml 文件中所有绑定的对象。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-09-02
    • 2015-05-20
    • 2015-10-22
    • 2023-03-24
    • 2017-11-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多