Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Force context menu to recreate child controls each time it opens

I have a context menu which contains a both a OneTime, one way binding and a second, non-OneTime two way binding to the same property. The goal is to have a color editor which displays the initial color value, and allows the user to change the selected value while still being able to compare it to the original.

This works well the first time the context menu is opened, but the menu doesn't seem to fully recreate itself each time it is opened (cached?). Instead, it "remembers" the original binding value, instead of doing another OneTime binding from the source to get the new "initial" value.

Is there a way to force a context menu to fully recreate its contents each time it is opened?

like image 430
aswanson Avatar asked Dec 25 '22 22:12

aswanson


1 Answers

I was able to quickly do this by creating a Style for the ContextMenu that sets its DataContext to null when it is hidden. This will cause the Bindings to re-run when it is opened, as they will have a new source. If you set the DataContext explicitly for the ContextMenu, you'll have to move that to a setter:

<ContextMenu>
    <ContextMenu.Style>
        <Style TargetType="{x:Type ContextMenu}">
            <Style.Triggers>
                <Trigger Property="IsOpen" Value="False">
                    <Setter Property="DataContext" Value="{x:Null}" />
                </Trigger>
            </Style.Triggers>
        </Style>
    </ContextMenu.Style>
    <MenuItem Header="{Binding Color, Mode=OneTime}" />
</ContextMenu>
like image 134
Abe Heidebrecht Avatar answered Jun 01 '23 01:06

Abe Heidebrecht