I have WebView2 control in my WPF application. I want to create a button programmatically at my cursor position.
Button ks = new Button();
ks.Width = 25;
ks.Height = 15;
ks.Content = "Add";
ks.Background = Brushes.Red;
ks.Margin = new Thickness(k.X, k.Y, 0, 0);
grid.Children.Add(ks);
But it seems that my button is created under WebView2 control, and I'm not able to see it.
How can I create a button over my WebView2 control?
It's a little bit tricky, but possible. I'll do it in XAML, but you can rewrite it as you need(create button or just switch the visibility).
The main idea is to wrap the Button
with a PopUp
. Pop up belongs not to the visual and being handled separately.
To get the feeling it's simple button you will need to handle some edge cases such as minimize, maximize, move, deactivate window.
So for the window do attach event handlers for Activated
, Deactivated
, StateChanged
and LocationChanged
events(you can also create a behavior for all code behinds to handle it in XAML).
private void Window_Activated(object sender, EventArgs e)
{
//Dispatcher we need for window change the size first
Dispatcher.BeginInvoke((Action)(() => {
popUpOver.IsOpen = true;
}));
}
private void Window_Deactivated(object sender, EventArgs e)
{
popUpOver.IsOpen = false;
}
private void Window_StateChanged(object sender, EventArgs e)
{
popUpOver.IsOpen = this.WindowState != WindowState.Minimized;
}
private void Window_LocationChanged(object sender, EventArgs e)
{
var offset = popUpOver.HorizontalOffset;
popUpOver.HorizontalOffset = offset + 1;
popUpOver.HorizontalOffset = offset;
}
<Popup x:Name="popUpOver" IsOpen="True" StaysOpen="True" Placement="RelativePoint" PlacementRectangle="300,300,500,500">
<Button Content="OVER" Width="100" Height="30"/>
</Popup>
PopUp moving was taken by: How can I move a WPF Popup when its anchor element moves?