[英]One View with Runtime Changing ViewModels
我正在做一个商务UWP应用,其中有来自各个表的大量数据输入。 尽管要填写的数据发生了变化,但视图的基本布局始终是一致的。 在我看来,应该很容易加载View,然后在运行时换出VM?
当我需要做的就是更改视图模型并使用模板选择器时,我实质上是在尝试以相同的方式针对多个条目表单更新同一页面?
我之所以问是因为我从未见过有人这样做,但是对我而言,MVVM的要点之一就是您可以轻松地将其交换出去。 有人对此有任何意见或经验吗?
您只需更改绑定xaml UI的ViewModel
即可更新View。 这是一个简单的例子来澄清它。
我有一个TestModel
类,
public class TestModel
{
public string ShowText { get; set; }
}
这是XAML,
<Page.DataContext>
<viewmodel:TestViewModel/>
</Page.DataContext>
<Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
<ListView ItemsSource="{Binding ViewModelList}">
<ListView.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding ShowText}"/>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
</Grid>
如果要更改视图数据,则只需操作TestViewModel
即可更改数据以更新View内容。 在此示例中,我使用DispatcherTimer
更改ViewModel,
这是ViewModel
类,
public TestViewModel()
{
ViewModelList = new ObservableCollection<TestModel>();
ViewModelList.Add(new TestModel { ShowText = "this is first test" });
ViewModelList.Add(new TestModel { ShowText = "this is second test" });
ViewModelList.Add(new TestModel { ShowText = "this is third test" });
//Create a timer to update the data source.
var dispatcherTimer = new DispatcherTimer();
dispatcherTimer.Tick += dispatcherTimer_Tick;
dispatcherTimer.Interval = new TimeSpan(0, 0, 2);
dispatcherTimer.Start();
}
private void dispatcherTimer_Tick(object sender, object e)
{
ViewModelList.Add(new Models.TestModel() { ShowText = "this is the added item" });
}
如果要通过ViewModel
类中属性的更改来自动更新View,则可能需要实现INotifyPropertyChanged
接口。 这是ViewModel
类的示例代码,
public class TestViewModel : INotifyPropertyChanged
{
public TestViewModel()
{
ViewModelList = new ObservableCollection<TestModel>();
ViewModelList.Add(new TestModel { ShowText = "this is first test" });
ViewModelList.Add(new TestModel { ShowText = "this is second test" });
ViewModelList.Add(new TestModel { ShowText = "this is third test" });
var dispatcherTimer = new DispatcherTimer();
dispatcherTimer.Tick += dispatcherTimer_Tick;
dispatcherTimer.Interval = new TimeSpan(0, 0, 2);
dispatcherTimer.Start();
}
int i;
public event PropertyChangedEventHandler PropertyChanged;
protected void RaisePropertyChanged(string name)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(name));
}
}
private void dispatcherTimer_Tick(object sender, object e)
{
i++;
ViewModelList = new ObservableCollection<TestModel>();
ViewModelList.Add(new TestModel { ShowText = "this is first test" + ">>" + i });
ViewModelList.Add(new TestModel { ShowText = "this is second test" + ">>" + i });
ViewModelList.Add(new TestModel { ShowText = "this is third test" + ">>" + i });
}
private ObservableCollection<TestModel> _ViewModelList;
public ObservableCollection<TestModel> ViewModelList
{
get
{
return _ViewModelList;
}
set
{
_ViewModelList = value;
RaisePropertyChanged("ViewModelList");
}
}
}
您可以从数据绑定主题和{Binding}标记扩展文档中了解更多信息。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.