How to find focused control in Silverlight

Joni Kettunen
Joni Kettunen used Ask the Experts™
on
I'm writing copy / paste functionality to a silverlight project. My project contains multiple pages, TextBox objects etc.

Now user wants to copy and paste selected text.

My problem is that I can't find which object has focus and without that information it is hard to copy text.

My xaml page has a grid which contains some user controls in different cells. The main grid handles right mouse menu with copy/paste functionality.

Since I am not working with WinForms, but in Silverlight. How can I find focused control?

Here are some code snippets:
<!-- Right mouse click opens copy/paste menu -->
<!-- Left mouse click just closes it -->
<Grid x:Name="LayoutRoot" Background="White" Loaded="LayoutRoot_Loaded" 
MouseRightButtonDown="LayoutRoot_MouseRightButtonDown"
        MouseLeftButtonDown="LayoutRoot_MouseLeftButtonDown">

<!-- Here are lots of elements created -->  

      <Canvas>
        <Popup x:Name="ContextMenu" Visibility="Collapsed" MouseRightButtonDown="LayoutRoot_MouseLeftButtonDown">
            <Border CornerRadius="5" BorderBrush="White" BorderThickness="1" Background="LightGray">
                <StackPanel >
                    <Button Content="Copy" Foreground="Black" Click="CopySelectedContent" />
                    <Button Content="Paste" Foreground="Black" Click="PasteFromClipboard" />
                </StackPanel>
            </Border>
        </Popup>
    </Canvas>
</Grid>

<!-- In code beside file there is a event handler -->
private void LayoutRoot_MouseRightButtonDown(object sender, MouseButtonEventArgs e)
{
    // I'd perefer capturing focused control here - before right mouse menu (canvas) is opened.
    // But sender is Grid hosting this canvas.
    Point position = e.GetPosition(null);
    e.Handled = true;
    ContextMenu.Visibility = Visibility.Visible;
    ContextMenu.IsOpen = true;
    ContextMenu.SetValue(Canvas.LeftProperty, (double)position.X);
    ContextMenu.SetValue(Canvas.TopProperty, (double)position.Y);  
}

Open in new window

Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
Commented:
FocusManager.GetFocusedElement();
Joni KettunenSenior Software Engineer

Author

Commented:
Exactly what I needed.

Thank you.

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial