I'm creating a custom control that has an ItemsSource
and DisplayMemberPath
properties, and in the ControlTemplate
there's a ListBox
control that's bound to this ItemsSourse
, I want to use the property specified by DisplayMemberPath
in this ListBox, unfortunately this doesn't work:
<ListBox ItemsSource="{Binding RelativeSource={RelativeSource TemplatedParent}, Path=ItemsSource}">
<ListBox.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding RelativeSource={RelativeSource TemplatedParent}, Path=DisplayMemberPath}"/>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
EDIT
As Mike Strobel suggested in the comment and as I read in some blog posts, I removed the ItemTemplate and provided only the DisplayMemberPath
in the ListBox but this doesn't even bint to the list (there's no scroll bar):
<ListBox ItemsSource="{Binding RelativeSource={RelativeSource TemplatedParent}, Path=ItemsSource}"
DisplayMemberPath="{Binding RelativeSource={RelativeSource TemplatedParent}, Path=DisplayMemberPath}"/>
I even hard-coded the DisplayMemberPath
value and still not working!, it's only working with List<string>
not List<CustomClass>
Solution
Pardon, I missed changing the DP type from IEnumerable<string>
to IEnumerable<object>
Thanks for the help!
Could it be that the TemplatedParent object isn't what you think it is? Have you tried traversing back by specified type?
<ListBox ItemsSource="{Binding RelativeSource={RelativeSource TemplatedParent}, Path=ItemsSource}">
<ListBox.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type **TYPE**}}, Path=DisplayMemberPath}"/>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.