【发布时间】:2017-11-10 10:43:50
【问题描述】:
我是使用 Prism WPF 的新手,并且对它的工作原理以及如何构建应用程序有基本的了解。
我在将数据绑定到视图中的控件时遇到问题,特别是使用“OnNavigatedTo”方法。
方法 1
我知道“OnNavigatedTo”方法是在构造函数之后调用的,但是当我调用存储库填充客户时,视图中的 ComboBox 是空的。
视图模型:
public class ViewAViewModel : BindableBase, INavigationAware
{
private readonly IRegionManager _regionManager;
private readonly IRepository _repository;
public List<Customer> Customers { get; set; }
public ViewAViewModel(IRepository repository, IRegionManager regionManager)
{
_repository = repository;
_regionManager = regionManager;
Customers = new List<Customer>();
}
private string _selectedCustomer;
public string SelectedCustomer
{
get { return _selectedCustomer; }
set { SetProperty(ref _selectedCustomer, value); }
}
public void OnNavigatedTo(NavigationContext navigationContext)
{
Customers = _repository.GetCustomers();
}
public bool IsNavigationTarget(NavigationContext navigationContext)
{
return true;
}
public void OnNavigatedFrom(NavigationContext navigationContext)
{
}
}
查看:
<UserControl x:Class="ModuleA.Views.ViewA"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:prism="http://prismlibrary.com/"
prism:ViewModelLocator.AutoWireViewModel="True">
<Grid>
<StackPanel>
<ComboBox ItemsSource="{Binding Customers}" DisplayMemberPath="Name" SelectedValuePath="Id" SelectedValue="{Binding SelectedCustomer}"></ComboBox>
</StackPanel>
</Grid>
</UserControl>
如果我通过构造函数初始化/填充“客户”,ComboBox 绑定工作正常,但是,当模块被添加到引导程序中的模块目录时,“客户”存储库方法被不必要地调用。我认为这并不理想。
方法 2
如果我在“客户”上使用“RaisePropertyChanged”,那么将数据绑定到 ComboBox 可以正常工作。
视图模型:
public class ViewAViewModel : BindableBase, INavigationAware
{
private readonly IRegionManager _regionManager;
private readonly IRepository _repository;
private List<Customer> _customers;
public List<Customer> Customers
{
get { return _customers; }
set
{
_customers = value;
RaisePropertyChanged();
}
}
public ViewAViewModel(IRepository repository, IRegionManager regionManager)
{
_repository = repository;
_regionManager = regionManager;
_customers = new List<Customer>();
}
private string _selectedCustomer;
public string SelectedCustomer
{
get { return _selectedCustomer; }
set { SetProperty(ref _selectedCustomer, value); }
}
public void OnNavigatedTo(NavigationContext navigationContext)
{
Customers = _repository.GetCustomers();
}
public bool IsNavigationTarget(NavigationContext navigationContext)
{
return true;
}
public void OnNavigatedFrom(NavigationContext navigationContext)
{
}
}
方法 2 是正确的方法吗?还是我错过了什么。
提前谢谢你。
【问题讨论】:
-
第二种方法是正确的。由于
Customers属性是一个绑定源,它必须引发PropertyChanged事件以通知绑定它应该更新其目标。这实际上是一个通用的数据绑定主题,与 Prism 或导航无关。 -
谢谢,为错误分类道歉。这是我的第一个问题。