我的第一个WPF在XAML中的ObjectDataProvider上工作得很好:
<ObjectDataProvider x:Key="WaitingPatientDS" ObjectType="{x:Type local:clsPatients}">
<ObjectDataProvider.ConstructorParameters>
<sys:Boolean>True</sys:Boolean>
</ObjectDataProvider.ConstructorParameters>
</ObjectDataProvider>然而,我不喜欢使用它,因为如果有一个连接错误,我不能捕获它,程序就会吐出来。
所以,我一直在尝试做的是直接在代码背后实例化集合对象……
public partial class MainWindow : Window
{
ListBox _activeListBox;
clsPatients oPatients;
public MainWindow()
{
oPatients = new clsPatients(true);然后...and在我的数据绑定中引用它:
<StackPanel x:Name="stkWaitingPatients" Width="300" Margin="0,0,0,-3"
DataContext="{Binding Mode=OneWay, Source={StaticResource local:oPatients}}">但是,我得到了“本地:找不到oPatients”。
So...what我引用它是不是做错了,以及/或者其他人如何完成这个数据绑定,这样我才能真正捕获连接错误,并将主窗体转换为用户友好的错误窗体?
谢谢!
发布于 2009-08-18 14:18:19
我会将数据访问逻辑移动到一个单独的服务中,也许还会完全移动到它自己的程序集中,以强制实现您想要的关注点分离。然后,我会让一个视图模型使用所述服务来检索数据,并将其公开给视图。然后,视图将简单地绑定到视图模型,而不关心数据是来自数据库还是其他什么。
我建议阅读关注点分离、服务定位器/依赖注入和MVVM。
发布于 2009-08-26 07:57:49
你会得到这个错误,因为oPatients不是一个StaticResource。它必须以ObjectDataProvider的方式在ResourceDictionary中定义,但作为类成员则不是。您可以将其公开为公共属性:
public clsPatients Patients { get; set; }然后直接绑定到它:
<!-- MainWindowRoot is the x:Name of your Window element. -->
<StackPanel x:Name="stkWaitingPatients" Width="300" Margin="0,0,0,-3"
DataContext="{Binding Patients, ElementName=MainWindowRoot, Mode=OneWay}">假设我没有犯一些愚蠢的错误,那应该是可行的。但是,它仍然不能解决您的问题,因为您正在将数据加载到构造函数中,这意味着任何异常都将导致clsPatients构造失败,进而导致MainWindow构造失败,您无法正确处理它,因为它是堆栈跟踪的rats,与合法的构造失败无法区分。
Kent是100%正确的:数据应该来自外部提供商。
您可能有资源限制,但即使您不能实现分层体系结构,您仍然可以建立良好的设计。至少,通过将数据加载到单独的数据提供程序类中,然后将完全格式的数据传递到窗口中,来建立关注点分离。这使您可以在发生故障的地方隔离故障,并使您的代码保持某种程度上的松散耦合。
public class PatientDataProvider
{
public PatientDataProvider(WhatItNeedsToConnect whatItNeedsToConnect)
{
// this doesn't connect because the constructor shouldn't fail because of a connection failure
}
public clsPatients GetPatientData(bool yesOrNo)
{
// this can fail because of a connection error or some other data loading error
}
}并以如下方式调用它:
PatientDataProvider provider = new PatientDataProvider(whatItNeedsToConnect);
clsPatients patients = null;
try {
patients = provider.GetPatientData(true);
MainWindow w = new MainWindow { Patients = patients; };
w.Show();
}
catch (WhateverExceptionGetsThrownByProvider e)
{
MessageBox.Show("Could not load patients: " + e.Message);
}此外,如果clsPatients是自刷新的,请确保它实现了适当的INotifyPropertyChanged或INotifyCollectionChanged,以便绑定目标在数据更改时进行更新。
https://stackoverflow.com/questions/1293755
复制相似问题