Question

So i have this issue:

  • I have created a UserControl (basically a textbox and label). This user control I am able to Bind using a Dependency Property.
  • I have a ListView in which I can put a textbox in the datatemplate and bind the "text" property to the binded value.

so far so good. but now if I try to put the UserControl into that very same scenario the DependencyProperty stops working.

Here is the code: [ListView]

<ListView x:Name="DtContactDetailListView" ItemsSource="{Binding}">
   <ListBox.ItemTemplate>
      <DataTemplate>
         <UserControl:tbx label="{Binding detail}" text="{Binding value}"/>
      </DataTemplate>
   </ListBox.ItemTemplate>
</ListView>

The binding in this situation works when its outside the listview, in other parts of the form... so its not an issue with my DepedencyProperty. Also substituting the UserControl for a Textbox, and adding the exact same Binding also works. But it doesn't work under this... why?!

UPDATE As requested, I have updated the code for the UserControl. Keep in mind this works perfectly when binding it to other elements on the window or page. Just doesn't work inside a listview.

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
Was it helpful?

Solution

Like I mentioned in the comment issue is in your UserControl, you have explicitly set DataContext of userControl to itself:

Me.DataContext = Me

So, binding label="{Binding detail}" looking for property detail in dataContext of UserControl (itself) and not in underlying dataContext of ListBoxItem.

You have to do explicit binding in case you want to look for item in DataContext of ListBoxItem like:

label="{Binding DataContext.detail,
                RelativeSource={RelativeSource Mode=FindAncestor, 
                                            AncestorType=ListBoxItem}}"

OR

You should remove setting DataContext to itself in UserControl.

You must have set it to bind with declared DP's. I would suggest to bind that using ElementName and remove setting DataContext. That way you don't have to give explicit binding and your UserControl will automatically inherit DataContext from its Visual parent.

<UserControl x:Name="myUserControl">
   <Label Content="{Binding label, ElementName=myUserControl}"/>
   <TextBlock Text="{Binding text, ElementName=myUserControl}"/>
</UserControl>
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top