FindAncestor不适用于ListView.ItemTemplate中的UserControl

时间:2010-10-05 11:41:47

标签: c# wpf user-controls binding findancestor

尝试使用FindAncestor模式将ItemTemplate中UserControl的属性绑定时,我遇到了一些问题。

我有以下代码:

<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路径错误:   未找到“内容”属性   'object'''String'   (的HashCode = -1920739956)”。   BindingExpression:路径=内容;   的DataItem = '字符串'   (的HashCode = -1920739956);目标要素   是'标签'(Name ='');目标财产   是'内容'(类型'对象')

MyUserControl只包含绑定到Content属性的Label:

<Grid>
    <Label Content="{Binding Content}" />
</Grid>

有人知道为什么UserControl的行为与Label控件不同吗? (或者至少可以帮助我看看我明显错过了什么?)

1 个答案:

答案 0 :(得分:0)

我认为问题出在你的MyUserControl上,<Label Content="{Binding Content}" />正在尝试为其datacontext找到'Content'属性,'string'为'ListViewItem'是字符串。

对于此示例,如果替换MyUserControl <Label Content="{Binding}" />中的绑定,这意味着将内容绑定到datacontext本身,则可以正常工作。