How To Set Focus on another window (MVVM)?
I have two window (Parent-Child). Parent window opens Child window so child window is focused
(i.e. top most window) but when child replies to Parent, Parent window is not focused (i.e. it's not on top).
I have created a attached property in a separate class like:
class FocusAttched:DependencyObject
{
public static DependencyProperty IsFocusedProperty =
DependencyProperty.RegisterAttached("IsFocused", typeof(bool), typeof(FocusAttched),
new UIPropertyMetadata(false, OnIsFocusedChanged));
public static bool GetIsFocused(DependencyObject dependencyObject)
{
return (bool)dependencyObject.GetValue(IsFocusedProperty);
}
public static void SetIsFocused(DependencyObject dependencyObject, bool value)
{
dependencyObject.SetValue(IsFocusedProperty, value);
}
public static void OnIsFocusedChanged(DependencyObject dependencyObject, DependencyPropertyChangedEventArgs dependencyPropertyChangedEventArgs)
{
((FrameworkElement)dependencyObject).Focus(); //My Code-Niranjan
// Removing hard coding
//TextBox textBox = dependencyObject as TextBox;
//bool newValue = (bool)dependencyPropertyChangedEventArgs.NewValue;
//bool oldValue = (bool)dependencyPropertyChangedEventArgs.OldValue;
//if (newValue && !oldValue && !textBox.IsFocused) textBox.Focus();
}
}
Now Attached this property to Parent window control (textbox)
Height="248" Margin="191,36,0,0" VerticalAlignment="Top" Width="249"/>
I am binding this attached property with a new property in View Model, for this reason I am creating a new bool property in View model.
bool _setFoucs;
public bool SetFocus {
get { return _setFoucs; }
set { _setFoucs = value; OnPropertyChanged(nameof(SetFocus)); }
}
I will set this property in Callback method.
Summery : Idea is that when Child window sends a message to Parent window, callback method will get called by Child, in this Callback I am setting this 'SetFocus' Property which is attached to TextBox of Parent window, OnPropertyChnage callback of Attached/Dependency property I am calling Focus() method of FrameworkElement( TextBox is Framework element).