如何将 DataTemplate 元素的可见性绑定到祖先元素的 ViewModel 属性?

How to binding DataTemplate element's visibility to ancestor element's ViewModel property?

我有一个数据模板:

    <DataTemplate x:Key="BMSelectedItemTemplate">
        <StackPanel Orientation="Horizontal">
            <TextBlock Text="*" Visibility=???/>
            <TextBlock Text="{Binding Name}"/>
        </StackPanel>
    </DataTemplate>

我有一个使用上述模板的 DataTemplateSelector:

    <BookmarkItemDataTemplateSelector x:Key="BookmarkItemDataTemplateSelector" SelectedItemTemplate="{StaticResource BMSelectedItemTemplate}" 
                                                                                      DropdownItemsTemplate="{StaticResource BMDropdownItemTemplate}" />

我在组合框中使用上述数据模板选择器:

        <StackPanel x:Name="splBookmark" Visibility="{Binding ShowBookmark, Converter={StaticResource BooleanToVisibilityConverter}}">
            <ComboBox x:Name="cbBookmark" ItemTemplateSelector="{StaticResource BookmarkItemDataTemplateSelector}"/>
        </StackPanel>

我的视图模型具有 ShowBookmark 和 ShowAsterisk 属性。我想将 BMSelectedItemTemplate 中“*”的可见性绑定到我的视图模型的 属性 ShowAsterisk。我怎么能那样做?我试过了:

Visibility="{Binding ShowAsterisk, Converter={StaticResource BooleanToVisibilityConverter}}"

但是没有用,它说数据模板找不到属性 ShowAsterisk,我认为这是有道理的,因为数据模板绑定到MBookmark对象列表,而在我的MBookmark class,没有ShowAsterisk的属性。 ShowAsterisk 是绑定到 splBookmark 堆栈面板的视图模型的 属性。

我的问题是如何将祖先元素的视图模型 属性 绑定到我的数据模板元素的可见性?

我无法使用相对路径祖先类型来查找我的组合框或堆栈面板,似乎我只能在我的相对源中使用 self 或 TemplateParent。我用silverlight.

谢谢!

在WPF中,您可以使用RelativeSource向上攀登可视化树。

假设您的物品容器是 ListBox:

Visibility="{Binding RelativeSource={RelativeSource AncestorType=ListBox}, 
                     Path=DataContext.ShowAsterisk,
                     Converter={StaticResource BooleanToVisibilityConverter}}"

在 UWP 应用中,RelativeSource 不可用,您可以改用 ElementName

首先,为控件命名:

<ComboBox Name="MyComboBox" />

然后,在绑定中使用它:

Visibility="{Binding ElementName=MyComboBox, 
                     Path=DataContext.ShowAsterisk,
                     Converter={StaticResource BooleanToVisibilityConverter}}"