我发现让数据绑定以 MVVM 样式为我的示例 WPF 应用程序工作具有挑战性。
问题:
以下示例中缺少什么?
细节:
基本结构:
型号:( Customer
其实无所谓)
视图模型: AllCustomersViewModel
看法: WizardWindowView
结构要素:
由 VM 公开: AllCustomers
(ObservableCollection 类型)
显示在视图上: ListView
想要绑定: ListView <-> AllCustomers
WizardWindowView.xaml:
<Window
...
...
<Window.Resources>
<CollectionViewSource x:Key="CustomerGroups" Source="{Binding Path=AllCustomers}"/>
</Window.Resources>
<Grid>
...
...
<aw:WizardPage Header="Step 1">
<ListView
ItemsSource="{Binding Source={StaticResource CustomerGroups}}"/>
</aw:WizardPage>
...
...
</Grid>
</Window>
我已经花了 10 多个小时试图了解数据绑定是如何完成的,并且觉得是时候寻求帮助了!
编辑
型号信息:
数据: customers.xml
模型: Customer.cs
数据访问: CustomerRepository.cs
所有客户视图模型:
readonly CustomerRepository _customerRepository;
public AllCustomersViewModel(CustomerRepository customerRespository) {...}
编辑 2
调用顺序:
App.xaml.cs.OnStartup() {.. new MainWindowViewModel("Data/customers.xml")..};
public MainWindowViewModel(string customerDataFile)
{
_customerRepository = new CustomerRepository(customerDataFile);
new AllCustomersViewModel(_customerRepository);
}
编辑 3
数据上下文:
在 App.xaml.cs 中:
MainWindow window = new MainWindow();
string path = "Data/customers.xml";
var viewModel = new MainWindowViewModel(path);
window.DataContext = viewModel;
在 MainWindow.xaml.cs(代码隐藏)中:
private void ShowWizardWindow(object sender, RoutedEventArgs e)
{
Views.WizardWindowView wizardWindow = new Views.WizardWindowView();
wizardWindow.DataContext = this.DataContext;
wizardWindow.Show();
}