FindAncestor does not work for UserControl in ListView.ItemTemplate
I'm having some issues when trying to bind a property of a UserControl in a ItemTemplate with a FindAncestor mode.
I have the following code:
<Window x:Class="TestUserControlBinding.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:system="clr-namespace:System;assembly=mscorlib"
xmlns:local="clr-namespace:TestUserControlBinding"
Title="MainWindow" Height="350" Width="525">
<Grid>
<ListView>
<ListView.ItemTemplate>
<DataTemplate>
<!--<Label Content="{Binding IsSelected, RelativeSource={RelativeSource FindAncestor, AncestorType=ListViewItem}}" />-->
<local:MyUserControl Content="{Binding IsSelected, RelativeSource={RelativeSource FindAncestor, AncestorType=ListViewItem}}" />
</DataTemplate>
</ListView.ItemTemplate>
<ListView.Items>
<system:String>First</system:String>
<system:String>Second</system:String>
<system:String>Third</system:String>
</ListView.Items>
</ListView>
</Grid>
</Window>
The commented Label line works ok (it displays True if it is selected in the ListView, and False otherwise).
The problem is with the MyUserControl which does not displays anything and VS says:
System.Windows.Data Error: 40 : Bindi开发者_开发技巧ngExpression path error: 'Content' property not found on 'object' ''String' (HashCode=-1920739956)'. BindingExpression:Path=Content; DataItem='String' (HashCode=-1920739956); target element is 'Label' (Name=''); target property is 'Content' (type 'Object')
MyUserControl simply contains a Label bound to the Content property:
<Grid>
<Label Content="{Binding Content}" />
</Grid>
Does anyone know why the UserControl behaves different than the Label control? (or at least can help me see what I obviously missing?)
I think the problem is with your MyUserControl, where with <Label Content="{Binding Content}" />
it is trying to find the 'Content' property to its datacontext which is 'string' as 'ListViewItem' is string.
For this sample if you replace the binding in MyUserControl <Label Content="{Binding}" />
which means that you bind content to the datacontext itself, will work.
精彩评论