Silverlight 绑定到父数据模板



我有用户数组和角色数组。对于每个用户,我正在渲染角色列表。我想将复选框绑定到某个用户属性。

这是我的代码(第 38 行):https://gist.github.com/sadgb/30e2b75f2fff159bc26e#file-gistfile1-xml-L38

为什么是这条线:

{Binding RelativeSource={RelativeSource Mode=FindAncestor,AncestorType=Grid}, Path=DataContext}

。绑定到角色类,而不是用户类?

绑定应该在第 21 行找到网格,其中具有 User 类型的 DataContext,不是吗?

还有另一种方法: -1. 为您的网格指定任何名称。2.然后像这样做你的绑定:

DataContext="{Binding ElementName=Gridname,Path=DataContext}"

这是您编辑的代码:

<DataTemplate DataType="usersService:User">
    <Grid Name="TheGrid">
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto"/>
            <RowDefinition Height="Auto"/>
            <RowDefinition Height="*"/>
        </Grid.RowDefinitions>
        <TextBlock Grid.Row="0" Text="{Binding UserId}"/>
        <telerik:RadListBox Grid.Row="1"
    ItemsSource= "{Binding RelativeSource={RelativeSource Mode=FindAncestor,AncestorType=users:UsersPage}, Path=RolesViewModel.Roles}" IsTextSearchEnabled="false">
            <telerik:RadListBox.ItemTemplate>
                <DataTemplate DataType="accessControlSubsystem:Role">
                    <StackPanel>
                        <CheckBox
                            IsChecked="{Binding ElementName=TheGrid,Path=DataContext , Converter={StaticResource CheckBoxToSelectedArrayConverter}, Mode=TwoWay}" Content="{Binding RoleName}" Tag="{Binding RoleId}" />
                    </StackPanel>
                </DataTemplate>
            </telerik:RadListBox.ItemTemplate>
        </telerik:RadListBox>
    </Grid>
</DataTemplate>

我想这将解决你的问题,或者至少给你一个好的开始。

我在您的代码中注意到的另一件事是,您没有在相对绑定中指定属性名称:

IsChecked="{Binding RelativeSource={RelativeSource Mode=FindAncestor,AncestorType=Grid}, Path=DataContext.PopertyName, Converter={StaticResource CheckBoxToSelectedArrayConverter}, Mode=TwoWay}"  Content="{Binding RoleName}" Tag="{Binding RoleId}" 

你能用"ancestorLevel"把关卡上移一个吗?

{Binding RelativeSource={RelativeSource Mode=FindAncestor,AncestorType=Grid}, AncestorLevel=1, Path=DataContext}

奥利弗

最新更新