Invoke UIElement’s Focus() Method From ViewModel

One of the things WPF developers often notice is inability to SetFocus on a particular control from the ViewModel. This problem can be however easily resolved using an attached property. Let’s examine the code.

We will begin by writing an attached property, for the purpose of example, named as IsFocused.

public class FocusExtension : DependencyObject
{
    public static bool GetIsFocused(DependencyObject dependencyObject) => (bool)dependencyObject.GetValue(IsFocusedProperty);
    public static void SetIsFocused(DependencyObject dependencyObject, bool value) => dependencyObject.SetValue(IsFocusedProperty, value);
    public static readonly DependencyProperty IsFocusedProperty =
            DependencyProperty.RegisterAttached("IsFocused", typeof(bool), typeof(FocusExtension), new PropertyMetadata(false, IsFocusChanged));
    private static void IsFocusChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
    {
       if ((bool)e.NewValue)
       {
          d as UIElement).Focus();
       }
    }
}

The sole objective of the attached property is to call the Focus() method of the attached UI element when the IsFocused Property Changes. Since the attached property is bindable from ViewModel, we can now set Focus to any control from our View Model. Am using Caliburn.Micro for my MVVM Implementation

View

<Grid>
        <Grid.RowDefinitions>
            <RowDefinition Height="20"/>
            <RowDefinition Height="20"/>
            <RowDefinition Height="20"/>
        </Grid.RowDefinitions>
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="*"/>
            <ColumnDefinition Width="*"/>
        </Grid.ColumnDefinitions>
        <Button Grid.Row="0" Grid.Column="0" Content="Set Focus" x:Name="SetFocusOnTextBox1"/>
        <TextBox Grid.Row="0" Grid.Column="1" Text="TextBox 1" ap:FocusExtension.IsFocused="{Binding IsTextBox1Focused}"  />
        <Button Grid.Row="1" Grid.Column="0" Content="Set Focus" x:Name="SetFocusOnTextBox2"/>
        <TextBox Grid.Row="1" Grid.Column="1" Text="TextBox 2" ap:FocusExtension.IsFocused="{Binding IsTextBox2Focused}"  />
        <Button Grid.Row="2" Grid.Column="0" Content="Set Focus" x:Name="SetFocusOnTextBox3"/>
        <TextBox Grid.Row="2" Grid.Column="1" Text="TextBox 3" ap:FocusExtension.IsFocused="{Binding IsTextBox3Focused}"  />
        <Button Grid.Row="3" Grid.Column="0" Content="Set Focus" x:Name="SetFocusOnTextBox4"/>
    </Grid>

ViewModel

public bool IsTextBox1Focused { get; set; }
public bool IsTextBox2Focused { get; set; }
public bool IsTextBox3Focused { get; set; }

public void SetFocusOnTextBox1()
{
   IsTextBox1Focused = true;
   NotifyOfPropertyChange(nameof(IsTextBox1Focused));
}

public void SetFocusOnTextBox2()
{
   IsTextBox2Focused = true;
   NotifyOfPropertyChange(nameof(IsTextBox2Focused));
}

public void SetFocusOnTextBox3()
{
   IsTextBox3Focused = true;
   NotifyOfPropertyChange(nameof(IsTextBox3Focused));
}

SharedSizeGroup: Managing Column Size across Grids

SharedSizeGroup is an underused WPF attribute, but one that can make life lot more easier when design WPF forms with multiple Grids that need to share a column size. Consider the screenshot below. The three pairs of Label and Textbox are in separate grids (with column width set to auto), resulting in an unorganized layout. It would far more better if the column width of first grid resizes itself to width of column in second grid.

Without SharedSizeGroup

You might often have to design more complex scenarios where you would love to retain the column size across Grids. This is where SharedSizeGroup comes into play. Let’s redefine our XAML with the attribute.

<Grid Margin="10,10,10,10">
        <StackPanel Grid.IsSharedSizeScope="True">
            <Grid>
                <Grid.ColumnDefinitions>
                    <ColumnDefinition Width="Auto" SharedSizeGroup="ABC"/>
                    <ColumnDefinition Width="*"/>
                </Grid.ColumnDefinitions>
                <TextBlock Text="Name"></TextBlock>
                <TextBox Grid.Column="1"/>
            </Grid>
            <Grid>
                <Grid.ColumnDefinitions>
                    <ColumnDefinition Width="Auto" SharedSizeGroup="ABC"/>
                    <ColumnDefinition Width="*"/>
                </Grid.ColumnDefinitions>
                <TextBlock Text="Full Name"></TextBlock>
                <TextBox Grid.Column="1"/>
            </Grid>
            <Grid>
                <Grid.ColumnDefinitions>
                    <ColumnDefinition Width="Auto" SharedSizeGroup="ABC"/>
                    <ColumnDefinition Width="*"/>
                </Grid.ColumnDefinitions>
                <TextBlock Text="Last Name"></TextBlock>
                <TextBox Grid.Column="1"/>
            </Grid>
        </StackPanel>
    </Grid>

 
Now the layout looks better organized.

With SharedSizeGroup

Leaders and Eye Specialist

How do I define leadership or how would like myself to be seen as a leader in the future. These are some of the questions I often come across. To be honest, it is quite hard to answer it precisely, after all, each ‘act’ of leadership depends on various factors including what the circumstances/situation demands. But if I was to generalize my perspective of leadership, or how I would like to be known as, I might be tempted to say, “I would like to be known as an eye specialist, rather than being a painter”, if I am allowed to answer figuratively.

The essence of the answer is quite simple and is inspired from works of Victor Frankl. A painter attempts to convey his visions of the world via his pictures, which is often interpretation of how he sees it. This is different from role of an eye specialist, whose role is to ensure that we see the world as it is, but with a much clearer and broader field of vision.

If one was to analyse the concept a bit deeper, isn’t that supposed to be what leaders need to be, especially with today’s increasingly competitive and highly skilled workforce ? The skill level and technical awareness of the teams are usually pretty high, and role of leaders has evolved from a taskmaster to being a servant leader. The role of an eye specialist might be that would take the concept of servant leadership a step higher. He aims in bringing more clarity to the team’s perspective on various things, in addition to broadening the field of perspective. The highly qualified cross-functional teams are then self sufficient to make better use of what they sees depending on each individual members proficiency in their trade. This collective, yet expert level contribution, would (in most cases) be far more effective than leaders own vision as he may not be the top ranked expert in each of the skills required for the task. It also would encourage the team members to take ownership of their work, rather than following someone else direction.

This concept has often worked well for me, having had the good fortune of leading teams, most often with team members, who were way ahead of me, both in terms of skill and experience. There are of course situation when you might have to paint the picture yourself, no second thoughts on that, but by donning the role of an eye specialist, you are actually encouraging team members to find more meaning to their work, which is essential to them enjoying their vocation and bringing the best out of them.