我在 Silverlight 中有一个订单详细信息表单,其中包含一个订单付款列表框。订单付款绑定到周围订单之外的它们自己的域数据源。我有一个按钮可以弹出一个 ChildWindow 控件来添加新的订单付款。订单付款具有与其关联的金额和付款方式。
表单加载正常,在下拉列表中显示数据表单中的所有付款方式以及金额的文本框。当我保存订单付款并尝试将其附加回订单详细信息 Order Payments 数据源时,我收到可怕的“无法附加实体,因为它已附加到另一个实体”错误。
这是 Add Order Payment 子窗口的 XAML:
<controls:ChildWindow.Resources>
<riaControls:DomainDataSource x:Key="paymentMethodsSource" QueryName="GetPaymentMethods" AutoLoad="True">
<riaControls:DomainDataSource.DomainContext>
<ds:CPSDomainContext />
</riaControls:DomainDataSource.DomainContext>
</riaControls:DomainDataSource>
</controls:ChildWindow.Resources>
<dataForm:DataForm x:Name="addOrderPaymentDataForm" AutoGenerateFields="False" AutoCommit="True" AutoEdit="True" CommandButtonsVisibility="None">
<dataForm:DataForm.EditTemplate>
<DataTemplate>
<StackPanel>
<dataForm:DataField Label="Payment Method">
<ListBox ItemsSource="{Binding Data, Source={StaticResource paymentMethodsSource}}"
DisplayMemberPath="Name"
SelectedItem="{Binding PaymentMethod, Mode=TwoWay}"
SelectionMode="Single"/>
</dataForm:DataField>
<dataForm:DataField Label="Amount">
<TextBox Text="{Binding Amount, Mode=TwoWay}" />
</dataForm:DataField>
</StackPanel>
</DataTemplate>
</dataForm:DataForm.EditTemplate>
</dataForm:DataForm>
这是添加订单付款屏幕的代码:
public AddOrderPaymentWindow() {
InitializeComponent();
NewOrderPayment = new OrderPayment();
addOrderPaymentDataForm.CurrentItem = NewOrderPayment;
addOrderPaymentDataForm.BeginEdit();
}
public OrderPayment NewOrderPayment { get; set; }
private void OKButton_Click(object sender, RoutedEventArgs e) {
NewOrderPayment.CreatedBy = "jkandiko";
NewOrderPayment.CreatedOn = DateTime.Now;
NewOrderPayment.ModifiedBy = "jkandiko";
NewOrderPayment.ModifiedOn = DateTime.Now;
var result = addOrderPaymentDataForm.CommitEdit();
this.DialogResult = true;
}
private void CancelButton_Click(object sender, RoutedEventArgs e) {
NewOrderPayment = null;
addOrderPaymentDataForm.CancelEdit();
this.DialogResult = false;
}
最后,这是尝试将新订单付款重新附加到订单详细信息屏幕的代码:
void add_Closed(object sender, EventArgs e) {
AddOrderPaymentWindow pay = (AddOrderPaymentWindow)sender;
if (pay.NewOrderPayment != null) {
Administration.Web.Services.CPSDomainContext context = (CPSDomainContext)orderPaymentDataGridSource.DomainContext;
context.OrderPayments.Add(pay.NewOrderPayment);
context.SubmitChanges();
}
}
我是否遇到了这个问题,因为 Order Payment 上有一个绑定到不同数据上下文的属性?考虑到子对象必须从 RIA 服务加载对象才能保存,我什至可以以这种方式添加子对象吗?我是否应该以某种方式将域数据源从订单详细信息页面传递给子控件以拥有一个数据源?还是我必须恢复到在代码中进行克隆才能获得新对象?