Modify content template in WP toolkit CustomMessageBox from code behind
I have a CustomMessageBox (from the Windows Phone Toolkit) in my WP8 app
which displays a control in its ContentTemplate that I need to initialise
from code behind. The dialog is created like this (that works perfectly):
CustomMessageBox dlg = new CustomMessageBox() {
Title = "TITLE",
Caption = "Caption",
ContentTemplate = (DataTemplate) App.Current.Resources["DlgTemplate"],
LeftButtonContent = "OK",
RightButtonContent = "Cancel",
IsFullScreen = true
};
My idea was getting the control by name (using the VisualTreeHelper) once
the dialog was loaded and initialise it:
dlg.Loaded += (s, e) => {
// GetVisualChild() is an extension method that uses the
VisualTreeHelper to
// recursively search the element with the specified name.
TextBlock tb = dlg.GetVisualChild<TextBlock>("tb");
tb.Text = "Some text";
};
The problem is that this code does not work all the time. It works most of
the time, but especially if the app just started up, I cannot retrieve the
control (TextBlock). I believe that this is some kind of race condition,
because I cannot debug the problem - it never occurs if I enable a break
point in GetVisualChild.
My question are:
Is the Loaded handler the correct way of doing this? If not, how would I
do this?
Is this really a race condition? Whan could I do about it?
Thanks in advance, Christoph
Edit: I am now using a very nasty hack which seems to work: By enqueueing
the operation in the dispatcher, it seems that I can "wait" for the dialog
to be "more loaded". However, I do not really like the solution:
dlg.Loaded += (s, e) => {
dlg.Dispatcher.BeginInvoke((Action) (() => {
TextBlock tb = dlg.GetVisualChild<TextBlock>("tb");
tb.Text = "Some text";
}));
};
No comments:
Post a Comment