Maddy
Maddy

Reputation: 590

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}}"

Upvotes: 0

Views: 422

Answers (1)

ManDani
ManDani

Reputation: 202

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.

Upvotes: 1

Related Questions