I've encountered a weird behavior in WPF. Even though there are quite a few ways to avoid this problem, I'm trying to better understand why it's happening:
I created a new WPF application, just added a button which has a ContextMenu:
<Grid>
<Button x:Name="btnTest" Margin="10,10,10,10"
MouseEnter="BtnTest_OnMouseEnter" MouseLeave="BtnTest_OnMouseLeave">
<Button.ContextMenu>
<ContextMenu x:Name="myContext">
<TextBlock Text="Context Menu Text"></TextBlock>
</ContextMenu>
</Button.ContextMenu>
</Button>
</Grid>
In the code behind I use MouseEnter to show the ContextMenu and MouseLeave to hide it:
private void BtnTest_OnMouseEnter(object sender, MouseEventArgs e)
{
myContext.PlacementTarget = btnTest;
myContext.Placement = PlacementMode.Bottom;
myContext.IsOpen = true;
}
private void BtnTest_OnMouseLeave(object sender, MouseEventArgs e)
{
myContext.IsOpen = false;
}
So now - I see the ContextMenu under the button when the mouse is on the button and it hides when the mouse leaves the button.
BUT when I click the button I get an exception
An unhandled exception of type 'System.StackOverflowException'
occurred in WindowsBase.dll
Question is - Why is the Mouse Click, specifically, triggering this exception? I don't have any code of mine running on the Click event, yet without clicking an exception doesn't occur...
BTW: Same will happen if I replace the Button with an Image for instance, so it doesn't seem to be caused by a specific control...
Change your XAML like this:
<Grid>
<Popup x:Name="myContext">
<TextBlock Text="Context Menu Text"></TextBlock>
</Popup>
<Button x:Name="btnTest" Margin="10,10,10,10"
MouseEnter="BtnTest_OnMouseEnter" MouseLeave="BtnTest_OnMouseLeave">
</Button>
</Grid>
I think there is a loop of this sort going on in your code:
you enter the button, the popup shows
you click, popup hides (default behavior of contextmenu)
button gets focus, popup is shown again
What happens if you set the ´StaysOpen´ property of the ContextMenu? If you then dont get this behavior anymore my suspicion is correct.
Related
I created a UserControl, and added a Button inside it removing the Background and Text properties:
<Button x:Name="Button"
HorizontalAlignment="Center"
Height="40"
VerticalAlignment="Center"
Width="40"
RenderTransformOrigin="0,-2"
Margin="0,0,0,0"
BorderBrush="{x:Null}"
Click="Button_Click"
Background="{x:Null}"/>
I also hadled the Button Click event as below:
private void Button_Click(object sender, RoutedEventArgs e)
{
Button.Content = new cross();
}
The above code fills the Button content with another UserControl which is a simple cross pic.
I have placed the UserControl with the Button into a MainWindow app and after pressing Button, it starts blinking - background is fluently changing between two colours. Beside my functionality from code works good. I just don't know how to get rid of that blinking background.
Before click:
After click:
You could set Focusable="False" at your Button to achive this.
But you should read about the Focusableproperty in the MSDN to check if it's ok for you. I guess you can't focus the Buttonusing the tab key anymore. But maybe that's not a problem for you.
I have a situation when I want to detect when a TextBox, anywhere in the application, has been brought into focus by the user clicking on it with the mouse, or touch. I have "solved" this by adding a global event handler like this:
Application.Current.MainWindow.AddHandler(UIElement.MouseLeftButtonUpEvent, new MouseButtonEventHandler(txt_MouseLeftButtonUp), true);
...
void txt_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
{
if (e.OriginalSource is TextBox)
{
// Do somthing
}
}
However, if the user clicks the edges of a textbox instead of in the middle, quite often an hosting control (Grid, Border etc.) receives the mouse event and somehow passes this on to the contained TextBox, that will handle it and receive focus. This makes the approach above fruitless as the TextBox will not be the e.OriginalSource in this case and I have found no way of identifying that a TextBox was brought into focus by click.
Deriving TextBox and overriding OnMouseDown for instance, will catch this event and I guess this path could be explored to find a solution to the problem but that would require me to use a custom TextBox everywhere.
Anyone out there with a nice solution for this?
This is an example that will trigger the problem. By clicking the edges of the TextBoxes, the grid will handle the mouse event and focus will be passed on to the TextBox.
<Grid>
<Grid HorizontalAlignment="Center"
VerticalAlignment="Center"
Background="Red">
<TextBox>2323</TextBox>
</Grid>
<Grid Margin="200,0,0,0"
HorizontalAlignment="Center"
VerticalAlignment="Center"
Background="Red" Focusable="False">
<TextBox>2323</TextBox>
</Grid>
</Grid>
The GotMouseCapture event seems to work:
AddHandler(UIElement.GotMouseCaptureEvent,
new MouseEventHandler(OnGotMouseCapture), true);
...
void OnGotMouseCapture(object sender, MouseEventArgs e)
{
if (e.OriginalSource is TextBox)
{
// ...
}
}
When I click on TextBox elements with the mouse this event handler is fired, however focus changes made via keyboard do not fire the event.
Simply handle the GotFocus event for each TextBox.
I have a Control that contains a Popup. I am trying to close the Popup whenever someone clicks outside of the Control. This is the part of my code that sets up the problem:
AddHandler(Mouse.PreviewMouseDownOutsideCapturedElementEvent, new MouseuttonEventHandler(HandleOutsideClick), true);
Now whenever I click in the Popup it causes PreviewMouseDownOutsideCapturedElementEvent to be raised. Am I misunderstanding this event? Is there something that I can do to have the Popup be considered a part of the Control so that it doesn't raise this event?
Does this work?
<Popup Name="Pop" LostFocus="ClosePop"/>
private void ClosePop(object sender, RoutedEventArgs e)
{
Pop.Visibility = Windows.UI.Xaml.Visibility.Collapsed;
}
Put the XAML code in your .xaml page and the C# code in the related .xaml.cs file.
Note: You may need to put the focus on the popup before this works, it may be done automatically; I haven't done this on popups, but I have done it on other objects.
Update: This works for me, clicking in the TextBox that says Test1 opens the Popup, and clicking in the TextBox labeled Test2 closes it:
<Grid Background="White">
<StackPanel>
<TextBox Foreground="Black" LostFocus="ClosePop" GotFocus="OpenPop" Height="50">Test1</TextBox>
<TextBox Foreground="Black" Height="50">Test2</TextBox>
</StackPanel>
<Popup Name="Pop" Height="50" Width="50">
<TextBlock Foreground="White" VerticalAlignment="Center" HorizontalAlignment="Center">Pop!</TextBlock>
</Popup>
</Grid>
private void ClosePop(object sender, RoutedEventArgs e)
{
Pop.IsOpen = false;
}
private void OpenPop(object sender, RoutedEventArgs e)
{
Pop.IsOpen = true;
}
I have a really strange behaviour, and I hope someone can help me out.
I have the following XAML layout:
<StackPanel Orientation="Horizontal">
<Menu>
<Menu.Items>
<MenuItem Padding="2,0,2,0">
<MenuItem.Header>
<Button Content="Details"
Click="Details_Click" />
</MenuItem.Header>
</MenuItem>
</Menu.Items>
</Menu>
<Button Content="Details"
Click="Details_Click" />
</StackPanel>
Please notice that both buttons have the same Event registered.
The Details_Click Event looks like this:
private void Details_Click(object sender, RoutedEventArgs e)
{
var viewer = new DictionaryViewer();
viewer.ShowActivated = true;
viewer.Show();
viewer.Topmost = true;
viewer.Topmost = false;
viewer.Activate();
viewer.Focus();
e.Handled = true;
return;
}
Now I am facing the problem, even with all the code from above the Window doesnt show up activated when I press the button inside the Menu but outside of it works with just .Activate();.
(How I know that window isnt activated: need 2 clicks to close/minimize/maximize it)
Why would my XAML Layout ruin the Activation of the DictionaryViewer(); window, with the button inside Menu?
(To your information the DictionaryViewer is totally empty, its a fresh window nothing implemented yet)
Edit:
Yes, I know there is the MenuItem_Click Event that may make it work, but I need/want the button inside the Menu how can I fix this issue?
THe reason this is happening is because the Button inside the MenuItem is gaining Focus after the Window has opened.
If you set the Focusable property of the button inside MenuItem, this fixes the issue.
E.g.
<StackPanel Orientation="Horizontal">
<Menu>
<Menu.Items>
<MenuItem Padding="2,0,2,0">
<MenuItem.Header>
<Button Content="Details"
Click="Details_Click"
Focusable="False" />
</MenuItem.Header>
</MenuItem>
</Menu.Items>
</Menu>
<Button Content="Details"
Click="Details_Click" />
</StackPanel>
Here I have sample window with a grid. I need to capture event when key is pressed. But it is not raising when I click grid area and then press key. It will work only if Textbox is focused. I know it will work if I capture it from Window. But I have other application with few usercontrols and I need to capture it from distinct ones. I tried to set Focusable.false for Window and true for Grid but it not helps.
Any solutions?
<Window x:Class="Beta.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525" Closed="Window_Closed_1" Focusable="False">
<Grid KeyDown="Grid_KeyDown_1" Focusable="True">
<TextBox x:Name="tbCount" HorizontalAlignment="Left" Height="35" Margin="310,49,0,0" TextWrapping="Wrap" Text="TextBox" VerticalAlignment="Top" Width="83"/>
</Grid>
Right this is weird. This is clearly a focus problem, still I can not understand why the grid do not take Focus, even when we click on it.
Though there is a workaround: create an handler for the loaded event of the grid:
<Grid x:Name="theGrid" KeyDown="Grid_KeyDown_1" Focusable="True" Loaded="TheGrid_OnLoaded">
And then force focus in your code behind:
private void TheGrid_OnLoaded(object sender, RoutedEventArgs e)
{
theGrid.Focus();
}
Your keydown event will work after that.
Hope it helps.
I had the same issue with a Universal Windows Platform (UWP) app. I attached the event to a grid in XAML but it would only work when the focus was on the TextBox. I found the answer (not just a workaround) on MSDN: https://social.msdn.microsoft.com/Forums/en-US/56272bc6-6085-426a-8939-f48d71ab12ca/page-keydown-event-not-firing?forum=winappswithcsharp
In summary, according to that post, the event won't fire because when focus to the TextBox is lost, it's passed higher up so the Grid won't get it. Window.Current.CoreWindow.KeyDown should be used instead. I've added my event handlers to the page loaded event like this:
private void Page_Loaded(object sender, RoutedEventArgs e)
{
Window.Current.CoreWindow.KeyDown += coreWindow_KeyDown;
Window.Current.CoreWindow.KeyUp += CoreWindow_KeyUp;
}
This works as expected for me.
I tried using the Focus Method too, to no avail, until I set the Focusable property to true ( It was default to False. )
I had the same problem, I've used PreviewKeyDownevent and it worked for me.