我正在尝试填充用户控件中的标签。我的用户控件的代码隐藏创建了一个对象,我正在尝试将标签内容绑定到该对象中的属性。创建对象的类实现了INotifyPropertyChanges
,并且有几个公共属性。我在XAML中创建了绑定,Visual Studio已经接受了这一点,intellisense为我提供了要绑定的属性。但是,当我运行时,标签都是空白的。
如果我直接在代码中创建一个属性,然后从对象调用(并适当地更改我的datacontext),它就可以工作。
我不是太有经验的WPF -我一定错过了什么,但我只是不知道什么?!
当我的XAML看起来像这样时,两个标签都没有填充。如果我将数据上下文调整到控件而不是instrument
对象,则ConStatus
标签会适当地填充(但不会更新,因为用户控件没有实现INotifyPropertyChange
:
<WrapPanel Grid.Row="1" DataContext="{Binding instrument}">
<Label Name="PortName" Width="100" Content="{Binding ConnectionString}" HorizontalAlignment="Right"/>
<Label Name="ConStatus" Width="200" Content="{Binding UniName}" HorizontalAlignment="Left"/>
</WrapPanel>
我的代码隐藏看起来像这样:
Public Class UnifaceControl
Inherits UserControl
Public instrument As UnifaceModel
Sub New()
' This call is required by the designer.
InitializeComponent()
' Add any initialization after the InitializeComponent() call.
FindUniface("uniface")
End Sub
Public Sub FindUniface(Portname As String)
instrument = New UnifaceModel(Portname)
instrument.Connect()
End Sub
ReadOnly Property UniName
Get
Return instrument.Connected
End Get
End Property
End Class
下面是UnifaceModel对象的示例:
Public Class UnifaceModel
Implements INotifyPropertyChanged
Shared Log As NLog.Logger = NLog.LogManager.GetCurrentClassLogger()
Dim _ConnectionString As String
Public Property ConnectionString As String
Get
Return _ConnectionString
End Get
Set(value As String)
_ConnectionString = value
OnPropertyChanged()
End Set
End Property
Public Event PropertyChanged As PropertyChangedEventHandler Implements INotifyPropertyChanged.PropertyChanged
Protected Sub OnPropertyChanged(<CallerMemberName> Optional propertyName As String = Nothing)
RaiseEvent PropertyChanged(Me, New PropertyChangedEventArgs(propertyName))
End Sub
1条答案
按热度按时间ugmeyewa1#
instrument
必须是一个 property 才能绑定到它:但是你还需要在某处设置控件或其父窗口的
DataContext
:由于您当前绑定到
UserControl
本身和instrument
的属性,因此不应将DataContext
绑定到instrument
: