I have seen a few posts addressing how to remove an UserControl that has been added during runtime, but my problem is a little different. I have a UserControl that consists of an image with a small "x" button on the top right corner that is used to remove itself (the UserControl) from its parent canvas. Also to note is that the UserControl is added during runtime when the user doubleclicks on a ListboxItem. I have a Click event handler for the top right corner button but this code is not running at all. I know this because I have a breakpoint in this code which is not reached when I click the button.
So,
Why isn't the click event of the remove button being handled?
Maybe there is a better way to implement this. Please advise.
Here's the code used for adding it:
private void MyListBox_MouseDoubleClick(object sender, System.Windows.Input.MouseButtonEventArgs e)
{
if (e.OriginalSource.ToString() == "System.Windows.Controls.Border" || e.OriginalSource.ToString() == "System.Windows.Controls.Image" || e.OriginalSource.ToString() == "System.Windows.Controls.TextBlock")
{
Expression.Blend.SampleData.MyCollection.Dataset lbi = ((sender as ListBox).SelectedItem as Expression.Blend.SampleData.MyCollection.Dataset);
var new_usercontrol = new MyUserControl();
new_usercontrol.MyImageSourceProperty = lbi.Image;
MyCanvas.Children.Add(new_usercontrol);
Canvas.SetLeft(new_usercontrol, 100);
Canvas.SetTop(new_usercontrol, 100);
Canvas.SetZIndex(new_usercontrol, 100);
}
}
The following is the cs code for the UserControl:
public partial class ModuleElement : UserControl
{
public ImageSource MyProperty
{
get { return (ImageSource)this.image.Source; }
set { this.image.Source = value; }
}
public ModuleElement()
{
this.InitializeComponent();
}
private void RemoveButton_Click(object sender, RoutedEventArgs e)
{
((Canvas)this.Parent).Children.Remove(this);
}
}
The XAML:
<Grid x:Name="LayoutRoot">
<Image x:Name="image" />
<Button x:Name="RemoveButton" Content="X" HorizontalAlignment="Right" Height="17.834" Margin="0" VerticalAlignment="Top" VerticalContentAlignment="Center" HorizontalContentAlignment="Center" Click="RemoveButton_Click">
</Button>
</Grid>
Thanks in advance,
Bryan
So I tried your code here exactly except for some name changes and could not reproduce your issue. In my personal experience your issue here has to be that for some reason the event for the click isn't subscribed to properly. For this I would go into designer for the user control, wipe out the current event for the button and double click in the designer event textbox such that VS or Blend generates all the code necessary for a proper subscription.
I have created a sample based on your code here. Feel free to pull it down and take a look to see if you can find any inconsistencies.
As far as a better way to implement this, check out the good old MVVM pattern and the MVVM Light Toolkit. With this you can have a central ViewModel class that will handle all of your button commands and binding without code behind.
Related
I have a UserControl with a number of StackPanel's. I like to hide specific panels depending on the user action. A StackPanel which is visible on startup gives me a number of working buttons. The buttons have click events in the code behind file. After collapsing the panel and then making it visible again the buttons no longer work. Here is a part of my UserControl:
<StackPanel x:Name="buttonPanel" Orientation="Horizontal">
<Button x:Name="ReMindNodeNotes" Content=""
FontFamily="Segoe UI Symbol" FontSize="14" Foreground="#FF292323"
HorizontalAlignment="Left" BorderThickness="1" Padding="0"
UseLayoutRounding="True" Click="NoteClicked" />
<Button x:Name="ReMindNodeRemove" Content=""
FontFamily="Segoe UI Symbol" FontSize="14" Foreground="#FF292323"
HorizontalAlignment="Left" BorderThickness="1" Padding="0"
UseLayoutRounding="True" Click="RemoveClicked" />
</StackPanel>
And here is the code (for now just some text):
private void NoteClicked(object sender, RoutedEventArgs e)
{
System.Diagnostics.Debug.WriteLine("NoteClicked...");
}
private void RemoveClicked(object sender, RoutedEventArgs e)
{
System.Diagnostics.Debug.WriteLine("RemoveClicked...");
}
I have been looking for a solution the last two days. No luck so far. Who can help...?
THX Peter
Follow up 1...
Here is the code for collapsing the panel:
private void MoreClicked(object sender, RoutedEventArgs e)
{
System.Diagnostics.Debug.WriteLine(this.nodeName);
this.buttonPanel.Visibility =
this.buttonPanel.Visibility ==
Visibility.Visible ? Visibility.Collapsed : Visibility.Visible;
}
It works if the buttonPanel has focus. If the focus is on another panel it does not. Furthermore, what I probably should have mentioned... is that users can create multiple instances of the user control.
THX
Follow up 2...
I continue working on a solution of course... ;-) and I found a solution, which however is not the solution I want. Let me explain.
Users can interactively create multiple instances of the user control mentioned before. When a new instance is created, that instance gets focus. Now every instance has its own set of buttons which are on a stackpanel. When the focus goes to another instance I want the panel of the previous instance to collapse. The focus should then be set to the new (or selected existing) instance.
When I do this manually, it works! When I try to achieve this through the GotFocus and LostFocus events however, it does not. Here is the code for the manual solution (which works):
private void MoreClicked(object sender, RoutedEventArgs e)
{
this.buttonPanel.Visibility =
this.buttonPanel.Visibility ==
Visibility.Visible ? Visibility.Collapsed : Visibility.Visible;
}
Here are the LostFocus and GotFocus events:
private void NodeGotFocus(object sender, RoutedEventArgs e)
{
this.buttonPanel.Visibility = Visibility.Visible;
}
private void NodeLostFocus(object sender, RoutedEventArgs e)
{
this.buttonPanel.Visibility = Visibility.Collapsed;
}
I really appreciate your help! THX again...
Thanks for your sample morincer. The problem however is a little more complex. Let me try to explain the solution which I found after some more research. Maybe other developers can benefit from it as well.
I added the GotFocus and LostFocus events to my userconctrol. If I click somewhere inside the usercontrol the focus changes every time. Strange as these events are only defined on the usercontrol itself and not it's children. I have several buttons and a textbox inside the usercontrol and when I for example click on one of the buttons of the usercontrol that has focus the LostFocus and GotFocus events are fired for usercontrol anyway.
The most important event for me in this case is the LostFocus event. When the usercontrol looses focus - for example to another control - I want the button panel to disappear. Since the LostFocus event fires every time a object inside the usercontrol is touched, I cannot distinguish between the situation in which I want to hide and show the buttons.
I got a little closer to a solution by changing the LostFocus event as follows:
private void LostFocus(object sender, RoutedEventArgs e)
{
Object fo = FocusManager.GetFocusedElement();
if (fo.GetType().ToString().Contains("TextBox") ||
fo.GetType().ToString().Contains("ScrollViewer"))
{
this.buttonPanel.Visibility = Visibility.Collapsed;
}
}
This covers most of the situations. When the cursor is positioned in the TextBox the button panel is closed. The button panel is also closed when the user clicks on the background. This seems to be a ScrollViewer (found through debugging the code). Can anyone explain this...?
The situation which is not covered however, is when a user clicks on another usercontrol. It does of course when the user clicks on the TextBox (see the code) but not when the user clicks on a button. I tried to compare sender and FocusManager.GetFocusedElement(). Problem is that the sender returns the usercontrol (which is what I am looking for) but the FocusManager.GetFocusedElement() returns the button that was pressed. Now I could ask for it's parent which is a border then ask for the borders parent which is a stack panel and so on until I arrive at the usercontrol. A code behind file however was introduced with the idea to split design and logic while this solution would tie them together again. If I would change the XAML I would have to change the logic as well. Doesn't seem to be the right solution to me.
I found a solotion by giving every usercontrol a unique name in the constructor. I then give all the buttons unique names as well (I don't use them in my code anyway) starting with the name of the usercontrol. This then gives me the possibility to compare names at runtime and determine whether the focus has changed to another instance of the usercontrol. Here is the code:
private void NodeLostFocus(object sender, RoutedEventArgs e)
{
Object fo = FocusManager.GetFocusedElement();
if (fo.GetType().ToString().Contains("ScrollViewer"))
{
this.buttonPanel.Visibility = Visibility.Collapsed;
}
else if (fo.GetType().ToString().Contains("TextBox"))
{
if (!((TextBox)fo).Name.Contains(this.nodeName))
{
this.buttonPanel.Visibility = Visibility.Collapsed;
}
}
else if (fo.GetType().ToString().Contains("Button"))
{
if (!((Button)fo).Name.Contains(this.nodeName))
{
this.buttonPanel.Visibility = Visibility.Collapsed;
}
}
}
Now this works! But…I don't like the solution. I am depending on names instead of a good architecture. Does anyone hove an idea how to compare the actual sender with the usercontrol that is the parent of the button pressed (FocusManager.GetFocusedElement())? Or any other solution that relies on good programming?
THX again
I have a C# WPF .NET 4 application that has an icon in the system tray. I am currently using the well-discussed WPF NotifyIcon, but the problem I am having is not dependent on this control. The problem is that .NET 4 simply does not allow (for the most part) a WPF ContextMenu object to appear over the top of the Windows 7 taskbar. This example illustrates the problem perfectly.
XAML:
<Window x:Class="TrayIconTesting.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="100" Width="400">
<Window.Resources>
<ContextMenu x:Key="TrayContextMenu" Placement="MousePoint">
<MenuItem Header="First Menu Item" />
<MenuItem Header="Second Menu Item" />
</ContextMenu>
<Popup x:Key="TrayPopup" Placement="MousePoint">
<Border Width="100" Height="100" Background="White" BorderBrush="Orange" BorderThickness="4">
<Button Content="Close" Click="ButtonClick"></Button>
</Border>
</Popup>
</Window.Resources>
<StackPanel Orientation="Horizontal">
<Label Target="{Binding ElementName=UseWinFormsMenu}" VerticalAlignment="Center">
<AccessText>Use WinForms context menu for tray menu:</AccessText>
</Label>
<CheckBox Name="UseWinFormsMenu" IsChecked="False" Click="UseWinFormsMenuClicked" VerticalAlignment="Center" />
</StackPanel>
</Window>
Code:
using System.Drawing;
using System.Windows;
using System.Windows.Controls.Primitives;
using System.Windows.Forms;
using ContextMenu = System.Windows.Controls.ContextMenu;
namespace TrayIconTesting
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
private ContextMenuStrip winFormsContextMenu;
public MainWindow()
{
InitializeComponent();
this.TrayIcon = new NotifyIcon
{
Icon = new Icon("Bulb.ico"),
Visible = true
};
this.TrayIcon.MouseClick += (sender, args) =>
{
switch (args.Button)
{
case MouseButtons.Left:
this.TrayPopup.IsOpen = true;
break;
case MouseButtons.Right:
if (!this.UseWinFormsMenu.IsChecked.GetValueOrDefault())
{
this.TrayContextMenu.IsOpen = true;
}
break;
}
};
}
private void ButtonClick(object sender, RoutedEventArgs e)
{
this.TrayPopup.IsOpen = false;
}
private void UseWinFormsMenuClicked(object sender, RoutedEventArgs e)
{
this.TrayIcon.ContextMenuStrip = this.UseWinFormsMenu.IsChecked.GetValueOrDefault() ? this.WinFormsContextMenu : null;
}
private ContextMenu TrayContextMenu
{
get
{
return (ContextMenu)this.FindResource("TrayContextMenu");
}
}
private Popup TrayPopup
{
get
{
return (Popup)this.FindResource("TrayPopup");
}
}
private NotifyIcon TrayIcon
{
get;
set;
}
private ContextMenuStrip WinFormsContextMenu
{
get
{
if (this.winFormsContextMenu == null)
{
this.winFormsContextMenu = new ContextMenuStrip();
this.winFormsContextMenu.Items.AddRange(new[] { new ToolStripMenuItem("Item 1"), new ToolStripMenuItem("Item 2") });
}
return this.winFormsContextMenu;
}
}
}
}
To see the problem make sure that the tray icon is always visible and not part of that Win7 tray icon popup thing. When you right click on the tray icon the context menu opens ABOVE the taskbar. Now right click one of the standard Windows tray icons next to it and see the difference.
Now, left click on the icon and notice that it DOES allow a custom popup to open right where the mouse cursor is.
Checking the "Use WinForms..." checkbox will switch the app to use the old ContextMenuStrip context menu in the Windows.Forms assembly. This obviously opens the menu in the correct place, but its appearance doesn't match the default Windows 7 menus. Specifically, the row highlighting is different.
I have played with the Horizontal and VerticalOffset properties, and with the "right" values you can make the context menu popup all the way at the bottom right of the screen, but this is just as bad. It still never opens where your cursor is.
The real kicker is that if you build this same sample targeting .NET 3.5 it works just as expected. Unfortunately, my real application uses many .NET 4 features, so reverting back is not an option.
Anyone have any idea how to make the context menu actually open where the cursor is?
After a little more searching I stumbled across this question & answer. I never thought to try the ContextMenu property on the NotifyIcon! While not ideal it will work well enough until WPF address the fact that the system tray is a useful part of applications. It will really be a shame to lose all the binding and command routing features provided by the WPF ContextMenu though.
It feels wrong to accept my own answer though, so I'm going to leave this open for a few more days.
Well, I'm glad didn't mark this as answered because I found a slightly better option for me. I found this article that details how to add icons to the System.Windows.Forms.MenuItem object. Now with just a little code I have a menu that perfectly matches system context menus!
I need to provide access key shortcut for several functions such as Save. To do this I have started by handling the KeyUp event of my root object which is a Grid called LayoutRoot (typically created as default in a Silverlight UserControl or Page).
I am using an MVVM pattern but for this I have added code in the code behind as such (this is UI interaction so it seems OK):
private void LayoutRoot_KeyUp(object sender, KeyEventArgs e)
{
switch (e.Key)
{
case Key.S:
if ((Keyboard.Modifiers & ModifierKeys.Windows) == ModifierKeys.Windows)
{
e.Handled = true;
// save
}
break;
case Key.C:
if ((Keyboard.Modifiers & ModifierKeys.Windows) == ModifierKeys.Windows)
{
e.Handled = true;
// clear fields
}
break;
}
}
I have used the Windows key because there are no shorcuts in the browser that use it as far as I know.
I implement the Save functionality on the Save button using a Command, therefore maintaining the MVVM pattern. E.g.
public RelayCommand CommandSavePtr { get; private set; }
CommandSavePtr = new RelayCommand(OnSavePtr);
private void OnSavePtr()
{
....
In XAML: -
<Button x:Name="SavePtrButton"
Command="{Binding CommandSavePtr}"
Style="{StaticResource StandardButtonStyle}"
IsEnabled="{Binding Ptr.HasErrors, Converter={StaticResource NotOperatorValueConverter}}">
<StackPanel Orientation="Horizontal">
<Image Source="/G4SPrisonerEscorting_ResourceDictionaries;component/images/accept.png" Style="{StaticResource SubPanelIconStyle}"/>
<TextBlock Text="Save"/>
</StackPanel>
</Button>
My problem now is that I don't know how to communicate to the ViewModel from my above KeyUp event to perform the same Save function that is perfomed when clicking the Save button.
Could anyone point me in the right direction.
BTW I am using GalaSoft's MVVM Light to do the Commanding.
This is an old question, but I thought I would answer it anyway if someone else stumbles upon the same problem.
It should be possible to fire the command for the button in the code-behind in the following manner:
SavePtrButton.Command.Execute(SavePtrButton.CommandParameter);
I'm creating a custom UserControl to be used inside a DataGrid editing template.
It looks like this:
<UserControl
x:Class="HR.Controls.UserPicker"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:tk="http://schemas.microsoft.com/wpf/2008/toolkit"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<Grid>
<TextBlock x:Name="PART_TextBox" Text="Hello WOrld" />
<Popup Width="234" Height="175" IsOpen="True" StaysOpen="True"
Placement="Bottom"
PlacementTarget="{Binding ElementName=PART_TextBox}"
>
<TextBox
x:Name="searchTextBox"
Text=">Enter Name<"/>
</Popup>
</Grid>
</UserControl>
edit:
I've narrowed down the code a bit.
It seems that if I put a Popup with textbox inside the CellEditingTemplate directly the textbox gets focus no problem. When I move that code into a UserControl I can no longer select the textbox when editing the cell.
Is the UserControl doing something funny with the focus ?
The problem is when i edit the cell in the datagrid I get the user control showing up but I can't click in the TextBox searchTextBox. When I click on it the popup closes and the cell goes back to default.
I have tried copying and pasting all the code inside the user control and pasting it directly into the CellEditingTemplate and that interacts the way it should.
I was just wondering if the UserControl did something weird that prevents a popup from gaining focus because it works as expected when directly placed in the CellEditingTemplate ?
Thanks,
Raul
Not sure if this will help anyone, but this helps if you have custom controls in the datagrid with a popup..... this fixed my problem, and it was one line of xaml. I spend the whole day re-reading this forum and then looking at the source for DataGridCell. Hope this helps.
<Style TargetType="{x:Type DataGridCell}">
<Setter Property="Focusable" Value="False"></Setter>
</Style>
I had a similar problem where a Popup embedded in a UserControl as a cell editing template would close when certain areas of it were clicked. The problem turned out to be that the WPF Toolkit (and presumably WPF4) DataGrid is very greedy with left mouse clicks. Even when you handle them and set Handled to true, the grid can interpret them as clicking into a different cell.
This thread has the full details, but the fix is to hook into DataGrid.CellEditEnding event and cancel the end edit:
private static void DataGrid_CellEditEnding(object sender, DataGridCellEditEndingEventArgs e)
{
if (e.Column.GetType() == typeof(DataGridTemplateColumn))
{
var popup = GetVisualChild<Popup>(e.EditingElement);
if (popup != null && popup.IsOpen)
{
e.Cancel = true;
}
}
}
private static T GetVisualChild<T>(DependencyObject visual)
where T : DependencyObject
{
if (visual == null)
return null;
var count = VisualTreeHelper.GetChildrenCount(visual);
for (int i = 0; i < count; i++)
{
var child = VisualTreeHelper.GetChild(visual, i);
var childOfTypeT = child as T ?? GetVisualChild<T>(child);
if (childOfTypeT != null)
return childOfTypeT;
}
return null;
}
Full credit for this goes to the Actipro thread.
Set FocusManager.IsFocusScope Attached Property on the Popup to True
I had a kinda simular problem, i created a usercontrol containing a textbox, a button and a calendar. Basicaly i create my own datepicker with custom validation logic.
I put this component in a CellEditingTemplate. When i pressed the button, the popup showed, but clicking the popup anywhere caused the cell te stop editing (because the popup was taking focus from the textbox). I solved it by adding code that sais that if the popup is open, the focus of the textbox may not be lost. This did the trick for me.
Also, the in the on loaded event handler of the usercontrol i give focus to the textbox.
In your case it's propably the Usercontrol itsefl that has focus.
protected override void OnPreviewLostKeyboardFocus(KeyboardFocusChangedEventArgs e) {
// Don't allow focus to leave the textbox if the popup is open
if (Popup.IsOpen) e.Handled = true;
}
private void Root_Loaded(object sender, RoutedEventArgs e) {
TextBox.Focus();
}
In my Silverlight application, I can't seem to bring focus to a TextBox control. On the recommendation of various posts, I've set the IsTabStop property to True and I'm using TextBox.Focus(). Though the UserControl_Loaded event is firing, the TextBox control isn't getting focus. I've included my very simple code below. What am I missing? Thanks.
Page.xaml
<UserControl x:Class="TextboxFocusTest.Page"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Loaded="UserControl_Loaded"
Width="400" Height="300">
<Grid x:Name="LayoutRoot" Background="White">
<StackPanel Width="150" VerticalAlignment="Center">
<TextBox x:Name="RegularTextBox" IsTabStop="True" />
</StackPanel>
</Grid>
</UserControl>
Page.xaml.cs
using System.Windows;
using System.Windows.Controls;
namespace PasswordTextboxTest
{
public partial class Page : UserControl
{
public Page()
{
InitializeComponent();
}
private void UserControl_Loaded(object sender, RoutedEventArgs e)
{
RegularTextBox.Focus();
}
}
}
I found this on silverlight.net, and was able to get it to work for me by adding a call to System.Windows.Browser.HtmlPage.Plugin.Focus() prior to calling RegularTextBox.Focus():
private void UserControl_Loaded(object sender, RoutedEventArgs e)
{
System.Windows.Browser.HtmlPage.Plugin.Focus();
RegularTextBox.Focus();
}
Plugin.Focus();
didn't work for me.
Calling
Dispatcher.BeginInvoke(() => { tbNewText.Focus();});
From the Load event worked.
thanks Santiago Palladino Dispatcher worked for me perfectly. What I am doing is:
this.Focus();
then
Dispatcher.BeginInvoke(() => { tbNewText.Focus();});
I solved putting in the control constructor:
this.TargetTextBox.Loaded += (o, e) => { this.TargetTextBox.Focus(); };
Are you sure you're not really getting focus? There's a known bug in Beta 2 where you'll get focus and be able to type but you won't get the caret or the border. The workaround is to call UpdateLayout() on the textbox right before you call Focus().
I would try adding a DispatcherTimer on the UserLoaded event that executes the Focus method a few milliseconds after the whole control has loaded; maybe the problem is there.
I also needed to call
Deployment.Current.Dispatcher.BeginInvoke(() => myTextbox.Focus());
interestingly this call is happening inside an event handler when I mouseclick on a TextBlock, collapse the TextBlock and make the TextBox Visible. If I don't follow it by a dispatcher.BeginInvoke it won't get focus.
-Mike
You code to set the focus is correct since if you add a button that calls the same code it works perfectly:
<StackPanel Width="150" VerticalAlignment="Center">
<TextBox x:Name="RegularTextBox" IsTabStop="True" />
<Button Click="UserControl_Loaded">
<TextBlock Text="Test"/>
</Button>
</StackPanel>
So I'm assuming this is something to do with Focus() requiring some kind of user interaction. I couldn't get it to work with a MouseMove event on the UserControl, but putting a KeyDown event to set the focus works (although the template doesn't update to the focused template).
Width="400" Height="300" Loaded="UserControl_Loaded" KeyDown="UserControl_KeyDown">
Seems like a bug to me....
For out-of-browser apps the System.Windows.Browser.HtmlPage.Plugin.Focus(); doesn't exist.
See my question here for other ideas.
It works for me in SL4 and IE7 and Firefox 3.6.12
Final missing "piece" which made focus to work (for me) was setting .TabIndex property
System.Windows.Browser.HtmlPage.Plugin.Focus();
txtUserName.IsTabStop = true;
txtPassword.IsTabStop = true;
if (txtUserName.Text.Trim().Length != 0)
{
txtPassword.UpdateLayout();
txtPassword.Focus();
txtPassword.TabIndex = 0;
}
else
{
txtUserName.UpdateLayout();
txtUserName.Focus();
txtUserName.TabIndex = 0;
}
My profile is not good enough to comment on #Jim B-G's answer but what worked for me was to add a handler for the Loaded event on the RichTextBox and inside that handler add
System.Windows.Browser.HtmlPage.Plugin.Focus();
<YourTextBox>.UpdateLayout()
<YourTextBox>.Focus();
However, it only worked on IE and FF. To get it work on Chrome and Safari, scroll to the bottom of this
I forgot one thing...I haven't found a way to force focus to your Silverlight application on the page reliably (it will work on some browsers and not on others).
So it may be that the Silverlight app itself doesn't have focus. I usually trick the user into clicking a button or something similar before I start expecting keyboard input to make sure that the silverlight app has focus.
I also ran into this problem, but it had arisen from a different case than what has been answered here already.
If you have a BusyIndicator control being displayed and hidden at all during your view, controls will not get focus if you have lines like
Dispatcher.BeginInvoke(() => { myControl.Focus();});
in the load event.
Instead, you will need to call that line of code after your BusyIndicator display has been set to false.
I have a related question here, as well as a solution for this scenario.
Indeed an annoying beheviour. I found a simple straightforward solution:
(VB code)
Me.Focus()
Me.UpdateLayout()
Me.tbx_user_num.Focus()
Me.tbx_user_num.UpdateLayout()
Each element here is essential, as per my project at least (VB2010 SL4 OutOfBrowser).
Credit to : http://www.dotnetspark.com/kb/1792-set-focus-to-textbox-silverlight-3.aspx
None of the above answers worked for me directly, what i did is that I added this event in in the MainPage() constructor:
this.Loaded += new RoutedEventHandler(MainPage_Loaded);
And handled it as follows:
void MainPage_Loaded(object sender, RoutedEventArgs e)
{
System.Windows.Browser.HtmlPage.Plugin.Focus();
RegularTextBox.Focus();
}
My Silverlight version is 4.