所以我有这个问题:
- 我创建了一个用户控件(基本上是一个文本框和标签)。我可以使用依赖属性来绑定此用户控件。
- 我有一个 ListView,可以在其中在数据模板中放置一个文本框并将“文本”属性绑定到绑定值。
到目前为止,一切都很好。但现在,如果我尝试将 UserControl 放入同一场景中,DependencyProperty 将停止工作。
这是代码:[列表显示]
<ListView x:Name="DtContactDetailListView" ItemsSource="{Binding}">
<ListBox.ItemTemplate>
<DataTemplate>
<UserControl:tbx label="{Binding detail}" text="{Binding value}"/>
</DataTemplate>
</ListBox.ItemTemplate>
</ListView>
这种情况下的绑定在列表视图之外、表单的其他部分中起作用......所以这不是我的 DepedencyProperty 的问题。另外,用 UserControl 替换 Textbox,并添加完全相同的 Binding 也可以。但它在这下不起作用......为什么?!
更新
根据要求,我更新了用户控件的代码。请记住,将其绑定到窗口或页面上的其他元素时,这非常有效。只是在列表视图中不起作用。
Public Sub New()
InitializeComponent()
Me.DataContext = Me
End Sub
'TextBox property
Public Shared ReadOnly tbxTextProperty As DependencyProperty = DependencyProperty.Register("text", GetType([String]), GetType(tbx), New FrameworkPropertyMetadata(String.Empty))
Public Property text() As [String]
Get
Return GetValue(tbxTextProperty).ToString()
End Get
Set(value As [String])
SetValue(tbxTextProperty, value)
End Set
End Property
就像我在评论问题中提到的那样,在您的 UserControl 中,您已明确设置DataContext
userControl 自身:
Me.DataContext = Me
所以,绑定label="{Binding detail}"
寻找财产detail
在 UserControl(本身)的 dataContext 中,而不是在 ListBoxItem 的底层 dataContext 中.
如果您想在 ListBoxItem 的 DataContext 中查找项目,则必须进行显式绑定,例如:
label="{Binding DataContext.detail,
RelativeSource={RelativeSource Mode=FindAncestor,
AncestorType=ListBoxItem}}"
OR
您应该删除设置DataContext
用户控件中的自身。
您必须将其设置为与声明的 DP 绑定。我建议绑定使用ElementName
并删除设置 DataContext。这样您就不必提供显式绑定,并且您的 UserControl 将自动从其 Visual 父级继承 DataContext。
<UserControl x:Name="myUserControl">
<Label Content="{Binding label, ElementName=myUserControl}"/>
<TextBlock Text="{Binding text, ElementName=myUserControl}"/>
</UserControl>
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)