gpt4 book ai didi

wpf - 在 silverlight/WP7 应用程序中使用 MVVM 样式模式

转载 作者:行者123 更新时间:2023-12-03 10:21:08 25 4
gpt4 key购买 nike

我正在编写一个应用程序,我试图使用 MVVM 风格的架构来处理我的数据绑定(bind)(尽管我没有使用 MVVM 特定的库,例如 MVVM Light)。我有一个类来存储我的应用程序所需的所有信息,然后为每个屏幕分配一个 View 模型到它的 DataContext,它只是选择特定屏幕所需的值,并在必要时格式化数据。

例如,主数据存储看起来像这样:

class DataStore {
int a, b, c;
string d;
DateTime e;
}

然后分配给特定屏幕的 View 模型,它只使用几个属性,就像
class MainScreenViewModel {
public int data1 { get { return App.DataStore.a * App.DataStore.c } }
public int data2 { get { return App.DataStore.e.Day } }
}

这似乎工作正常,当页面加载时,数据绑定(bind)按应有的方式填充。但是,它们不会在页面加载时自动更新。我已经在 DataStore 上实现了 INotifyPropertyChanged,但似乎更改事件并没有冒泡以反射(reflect)在 View 模型中。我敢肯定我会以一种非常糟糕的方式来解决这个问题,所以如果有人能帮助我指出正确的方向,我将不胜感激。我在网上阅读了一堆指南,但我似乎越来越困惑自己!

最佳答案

你必须执行 INotifyPropertyChanged并提高 PropertyChanged在您的虚拟机上。为此,您必须收听 DataStore.PropertyChanged .样本:

class MainScreenViewModel {
public int data1 { get { return App.DataStore.a * App.DataStore.c } }
public int data2 { get { return App.DataStore.e.Day } }


public MainScreenViewModel()
{
App.DataStore.PropertyChanged += (sender, e) =>
{
if (e.PropertyName == "a" || e.PropertyName == "c")
RaisePropertyChanged("data1");
if (e.PropertyName == "e")
RaisePropertyChanged("data2");
};
}

private void RaisePropertyChanged(string propertyName)
{
// raise it
}
}

这里唯一没有涉及的部分是 e.Day 时的场景。将在 DataStore 中更改.

你的方法本身并不坏,而且绝对足够好开始。

关于wpf - 在 silverlight/WP7 应用程序中使用 MVVM 样式模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6329089/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com