Ok so obviously there’s more to it, but here’s the basics. This is seemingly such a simple thing but it’s not working.
I have a Label.
I have a TextBox.
The ZIndex of the Label = “1”
The ZIndex of the TextBox = “0”
i.e. They are on top of one another and the TextBox is invisible.
When the user clicks on the LABEL (right now Via PreviewMouseLeftButtonDown but will be a command in ViewModel after this “works”) the application should set focus to the TextBox.
Simple right? Wrong…
If I have this code…it does NOT work.
private void inVisTxtBox_PreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
inVisTxtBox.Focus();
// TextBox_MouseDown(sender, e);
}
If I have this code…it DOES work
private void inVisTxtBox_PreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
inVisTxtBox.Focus();
// TextBox_MouseDown(sender, e);
MessageBox.Show("This is ridiculous");
}
And finally the XAML:
<Ctrls:AControl x:Class="<location of class>"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:CommandControls="clr-namespace:<location of custom controls>" VerticalAlignment="Stretch" HorizontalAlignment="Stretch">
<Grid Margin="0,15,15,15">
<!--<Button Height="50" Click="Button_Click">FOC</Button>-->
<TextBox x:Name="inVisTxtBox" Focusable="True" Grid.ZIndex="0" Width="100" Margin="5"/>
<Label Grid.ZIndex="1" Margin="5" Content="243234234234234" HorizontalAlignment="Left" Width="100" PreviewMouseLeftButtonDown="inVisTxtBox_PreviewMouseLeftButtonDown"
x:Name="KeyPress_TextBox"/>
</Grid>
</Ctrls:AControl>
EDIT
If I make the Label into a Templated Button with a label as it’s template it works:
<Button x:Name="KeyPress_TextBox" Grid.ZIndex="1" Margin="5" Content="243234234234234" HorizontalAlignment="Left" Width="100" Click="KeyPress_TextBox_Click">
<Button.Template>
<ControlTemplate TargetType="Button">
<Label Content="{TemplateBinding Content}"/>
</ControlTemplate>
</Button.Template>
</Button>
Why is that?
Must have something to do with the way the events route/bubble?
I have it working now by doing that…but I’m more curious what’s happening.
Also…none of the following works either:
Keyboard.Focus(inVisTxtBox);
FocusManager.SetFocusedElement(MainGrid,inVisTxtBox);
Keyboard.Focus(inVisTxtBox);
I copied your code and it works fine for me, even with previewmouseclick, something else seems to be the problem.
Likely throwing the message box up stops the focus from shifting to whatever it was going to shift to after the PreviewMouseLeftButtonDown event fires. Perhaps the UserControl itself is getting focus?