Need help with caliburn Message.Attach when TextBox gets focus
I have a TextBox that I am setting the focus on using an attached property bound to a property of the view model. The attached property calls "UIElement.Focus()" to set the focus. The problem is when the TextBox receives focus in this manner the "GotFocus" event doesn't fire. I am using Caliburn.Micro's Message.Attach to handle the event. Any ideas?
Here is the TextBox.
<TextBox x:Name="Test"
Grid.Column="0"
Text="{Binding Test, Converter={StaticResource TestToStringConverter}}"
AttachedProperties:FocusExtension.IsFocused="{Binding IsTestFocused}"
cal:Message.Attach="[Event GotFocus] = [Action OnGotFocus($eventargs)]; />
Here is the Attached Property (found on SO).
public static class FocusExtension
{
public static bool GetIsFocused(DependencyObject obj)
{
return (bool) obj.GetValue(IsFocusedProperty);
}
public static void SetIsFocused(DependencyObject obj, bool value)
{
obj.SetValue(IsFocusedProperty, value);
}
public static readonly DependencyProperty IsFocusedProperty =
DependencyProperty.RegisterAttached("IsFocused", typeof (bool), typeof (FocusExtension),
new UIPropertyMetadata(false, OnIsFocusedPropertyChanged));
private static void OnIsFocusedPropertyChanged(DependencyObject d, DependencyPropertyChangedE开发者_JAVA百科ventArgs e)
{
var uie = (UIElement)d;
if ((bool)e.NewValue)
{
uie.Focus();
}
}
}
I have tried this myself, and am able to replicate the issue. I'm not quite sure why this happens, it may have something to do with the user control's (i.e. the views) lifecycle. One option could be to extend your attached property so that it invokes a verb on your view model at the point at which it calls uie.Focus()
.
The name of the verb could be a dependency property on your FocusExtension
attached property, and could be set in the view.
精彩评论