简体   繁体   中英

Binding in ResourceDictionary not working

I have a ContextMenu in a ResourceDictionary . The ContextMenu should hide or show depending on the value of a view-model property, but it does not work.

This is my XAML code ( ControlBase derives from UserControl ):

<control1:ControlBase>
    <UserControl.Resources>
        <ResourceDictionary>
            <HierarchicalDataTemplate ItemsSource="{Binding InfraNetworkItems}">
                <StackPanel>
                    <StackPanel.ContextMenu>
                        <ContextMenu DataContext="{Binding PlacementTarget.DataContext,
                                         RelativeSource={RelativeSource Self}}">
                            <MenuItem Header="Delete"
                                      Visibility="{Binding
                                          DataContext.MyViewModel.DeleteEnabled,
                                          RelativeSource={RelativeSource Mode=FindAncestor,
                                              AncestorType=control1:ControlBase},
                                          Converter={StaticResource
                                              BooleanVisibilityConverter}}" />
                        </ContextMenu>
                    </StackPanel.ContextMenu>
                </StackPanel>
            </HierarchicalDataTemplate>
        </ResourceDictionary>
    </UserControl.Resources>
</control1:ControlBase>

DeleteEnabled is a bool property on the view-model.


My previous attempts of solving the problem are based on this assumptions:

The ContextMenu is inside a HierarchicalDataTemplate which has the ItemsSource set. My property is not a member of this ItemSource , it belongs to the view-model. Therefore I've tried this line of code, but without any effect:

Visibility="{Binding DataContext.MyViewModel.DeleteEnabled,
    RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=control1:ControlBase},
    Converter={StaticResource BooleanVisibilityConverter}}"

But if I copy the DeleteEnabled property from the view-model to the ItemSource object, it works:

Visibility="{Binding DeleteEnabled, Converter={StaticResource BooleanVisibilityConverter}}"

what is the DataContext of your view? If it's an instance of MyViewModel you have to change the path of your Binding. Please try this one:

<Visibility="{Binding DataContext.DeleteEnabled, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=control1:ControlBase}, Converter={StaticResource BooleanVisibilityConverter}}" />

With setting the path to DataContext you already have access to your viewmodel and of course to the DeleteEnabled-Property. Hope this helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM