我试图将我的W3CError类型对象的集合绑定到WPF ListView控件。
这是一个很好的小13线课......
Class W3CError Public Type As ErrorOrWarning Public Line As Integer Public Col As Integer Public Message As String Public MessageId As String Public Explanation As String Public Source As String Enum ErrorOrWarning ValidationError ValidationWarning End Enum End Class
它不起作用。我在Visual Studio的“输出”窗口中遇到了这些绑定错误:
System.Windows.Data错误:39: BindingExpression路径错误:'Line' 在'对象'上找不到的属性 ''W3CError'(HashCode = ...)'。 BindingExpression:路径=行; 的DataItem = 'W3CError' (的HashCode = ...);目标元素是 'TextBlock'(Name ='');目标财产 是'文字'(类型'字符串')
嗯,不,那不是财产。它只是公共的。我想这对WPF绑定来说还不够好?
我通过将我的班级延长到丑陋的69行属性样板来实现它......
Class W3CError Private _Type As ErrorOrWarning Private _Line As Integer Private _Col As Integer Private _Message As String Private _MessageId As String Private _Explanation As String Private _Source As String Enum ErrorOrWarning ValidationError ValidationWarning End Enum Public Property Type() As ErrorOrWarning Get Return _Type End Get Set(ByVal value As ErrorOrWarning) _Type = value End Set End Property Public Property Line() As Integer Get Return _Line End Get Set(ByVal value As Integer) _Line = value End Set End Property Public Property Col() As Integer Get Return _Col End Get Set(ByVal value As Integer) _Col = value End Set End Property Public Property Message() As String Get Return _Message End Get Set(ByVal value As String) _Message = value End Set End Property Public Property MessageId() As String Get Return _MessageId End Get Set(ByVal value As String) _MessageId = value End Set End Property Public Property Explanation() As String Get Return _Explanation End Get Set(ByVal value As String) _Explanation = value End Set End Property Public Property Source() As String Get Return _Source End Get Set(ByVal value As String) _Source = value End Set End Property End Class
有更好的方法吗?
答案 0 :(得分:4)
如果您使用C#我会说使用自动属性,但我认为它们不在VB中。
所以可能不是。您甚至可能希望更进一步,让您的类实现INotifyPropertyChanged,以便您的UI知道属性是否会发生变化。
答案 1 :(得分:1)
我不会将其称为更好方式,但您可以实施ICustomTypeDescriptor
并通过GetProperties
方法将您的字段公开为虚假属性。但是,如果你有几十个字段,它最终会减少代码。
最初由Robert Macnee发布,但后来被删除了。在这里恢复,因为它让我感兴趣...