我做了一个自定义控件,称为AddressForm,它继承自Control。该控件用于显示IAddress对象的字段。
最初,我是在Silverlight中创建此控件的,现在我正在尝试使其在WPF .net 4.5中运行。
该控件定义了9个不同的依赖项属性,除了一个属性外,其他所有属性均正常工作。自然,不起作用的是Address对象本身!
控件的Address属性从不接收任何值。我在地址的Getter中放置了一个断点,该属性被调用,地址对象不为null,但控件未收到它。
输出屏幕中没有异常,也没有错误消息。
控制 :
public class AddressForm : Control, INotifyPropertyChanged
{
[...]
public static readonly DependencyProperty AddressProperty = DependencyProperty.Register("Address", typeof(IAddress), typeof(AddressForm), new PropertyMetadata( AddressChanged));
public IAddress Address
{
get { return (IAddress)GetValue(AddressProperty); }
set { SetValue(AddressProperty, value); }
}
private static void AddressChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
//break-point here never gets hit
AddressForm form = d as AddressForm;
if (form != null)
form.OnAddressSet();
}
private void OnAddressSet()
{
//break-point here never gets hit
if (StateProvince != null && Address != null)
SelectedStateProvince = StateProvince.Where(A => A.StateProvince == Address.StateProvince).FirstOrDefault();
}
[...]
}
(其他DependencyProperty的设置方法相同,并且可以正常工作。)
xaml:
<Address:AddressForm Address="{Binding SelectedMFG.dms_Address, Mode=TwoWay}" ... />
SelectedMFG的类型为scm_MFG
数据对象:
public partial class scm_MFG
{
[...]
public virtual dms_Address dms_Address { get; set; } //break-point here never enables? Generated code from Entity TT
//Another attempt, trying to determine if the IAddress cast was the cause of the issue
//Address="{Binding SelectedMFG.OtherAddress}"
public IAddress OtherAddress
{
get {
return dms_Address as IAddress; //break-point here gets hit. dms_Address is not null. Control never receives the value.
}
}
}
public partial class dms_Address : IAddress, INotifyPropertyChanged { ... }
我的尝试:
我尝试以其他方式访问dms_Address属性。我可以在文本框中显示Address的值,这告诉我datacontext没有问题。
<TextBox Text="{Binding SelectedMFG.dms_Address.StreetName, Mode=TwoWay}" /> <!-- this value displays -->
我还尝试过更改依赖项属性的注册元数据。我不确定使用哪种正确的方法:PropertyMetadata,UIPropertyMetadata或FrameworkPropertyMetadata
DependencyProperty.Register("Address", typeof(IAddress), typeof(AddressForm), new PropertyMetadata(AddressChanged));
DependencyProperty.Register("Address", typeof(IAddress), typeof(AddressForm), new PropertyMetadata(null, AddressChanged));
DependencyProperty.Register("Address", typeof(IAddress), typeof(AddressForm), new UIPropertyMetadata(AddressChanged));
DependencyProperty.Register("Address", typeof(IAddress), typeof(AddressForm), new FrameworkPropertyMetadata(null, FrameworkPropertyMetadataOptions.Inherits, AddressChanged));
// and other FrameworkPropertyMetadataOptions, no difference
。
我相信我已经正确地完成了所有工作,并且应该可以正常工作。
是否有任何异常或错误跳出来?
我找到了解决方案。
我将表单上的地址依赖项属性从IAddress更改为Object。现在该属性已设置。似乎即使我正在返回IAddress对象,该窗体实际上正在接收的对象也是dms_Address的EntityWrapper。
该实体包装器也将强制转换为IAddress,所以我不确定为什么它会这样。我猜只是另一个实体陷阱。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句