Friday, July 26, 2019

WPF : How To Set Focus on another window (MVVM)


 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)

                      VerticalScrollBarVisibility="Visible" TextWrapping="Wrap" AcceptsReturn="True" HorizontalAlignment="Left"
                 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).

No comments:

Post a Comment

C# Record type: Something to remember while using record types

  Record in c# provide a concise and expressive way to create immutable data types, record is a keyword in c#, we can use this keyword with ...