Wednesday, November 26, 2008

Silverlight Threading and Events

$##$%^#$% Silverlight today is really making me tired. So I have this textbox? no big deal tha tis a search form. Users expect the return to make the form 'submit'. we know that is not exactly how Silverlight forms 'work' persay but we get the point right. no problem nothing a bit of code won't solve. so I make the 'search' button have a click event that validates the form and sents it to a class that deals with the data. and it works great.

then I make the text block have a keydown event so I can capture returns and send them along their way... if it is a return I just call the other event handler...

and one does a call to system which blows up. so the event in the key up looks like this:


private void SearchBox_KeyDown(object sender, KeyEventArgs e)
{
if (e.Key == Key.Enter)
{
SearchBtn_Click(sender, null);
}
}

but in the search btn we are trying todo an alert as I'm in a hurry and don't feel like making a nice silverlight message thingy so I just want todo this:


private void SearchBtn_Click(object sender, RoutedEventArgs e)
{
string SearchValue = SearchBox.Text.ToString();
if (SearchValue != "" && SearchValue.Length > 2)
{
DataBindMe.DataContext = CrossfaderUsers.RetrieveSearchUserList(SearchValue);
}
else
{
System.Windows.Browser.HtmlPage.Window.Alert(App.SEARCHTEXTINVALID);
}
SearchMessageBox.Visibility = Visibility.Collapsed;
}

this blows up from the keydown event apperently as it is not on the UI thread??? WT...? I mean really the 'click' event is on the UI thread but keydown is not? the error message is something to effect of namespace 'System' is not accessable due to the context? As far as I can tell by 30 minutes of googling is that this event some how is magically not on the UI thread so when I add this:


Dispatcher.BeginInvoke(delegate()
{
System.Windows.Browser.HtmlPage.Window.Alert(App.SEARCHTEXTINVALID);
});

it magically works???