尝试将 ItemTemplate 中的 UserControl 的属性与 FindAncestor 模式绑定时遇到一些问题。
我有以下代码:
<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>
注释标签行可以正常工作(如果在 ListView 中选择它,则显示 True,否则显示 False)。
问题出在 MyUserControl 上,它不显示任何内容,VS 说:
System.Windows.Data 错误:40:BindingExpression 路径错误:在“对象”“字符串”(HashCode=-1920739956)上找不到“内容”属性。绑定表达式:路径=内容;DataItem='String' (HashCode=-1920739956); 目标元素是'标签'(名称='');目标属性是“内容”(类型“对象”)
MyUserControl 只包含一个绑定到 Content 属性的 Label:
<Grid>
<Label Content="{Binding Content}" />
</Grid>
有谁知道为什么 UserControl 的行为与 Label 控件不同?(或者至少可以帮助我看看我明显错过了什么?)