开发者

Silverlight MVVM and dealing with FOCUS

I'm developing complex data entry forms with various pop-up lookups, etc. Because of different things - focus of certain controls get lost and I need some way to set focus in MVVM. So far I came up with attached property which I coded like this(actual dependency property declaration skipped):

private static void SetFocus(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            var textBox = d as TextBox;
            if (textBox != null)
            {
                textBox.Focus();
            }
        }

So, it's pretty simple. When property changes - focus get's set.

My view:

<TextBox Text="{Binding CurrentItem.SerialNumber, Mode=TwoWay, NotifyOnValidationError=True}" 
                     behaviors:TextBoxBehaviors.IsFocused="{Binding SecondaryControlFocus}"
                     Grid.Column="1" Grid.Row="2" Margin="1" Grid.ColumnSpan="2" TabIndex="2" />

As you see - I attach that behavior and Bind to "SecondaryControlFocus" property.

ViewModel:

public bool SecondaryControlFocus
        {
            get
            {
                return this.secondaryControlFocus;
            }

            set
            {
                this.secondaryControlFocus = value;
                this.RaisePropertyChanged(() => this.SecondaryControlFocus);
            }
        }

And c开发者_如何学Code how I set focus:

this.SecondaryControlFocus = !this.SecondaryControlFocus;

To me this code smells because I have to toggle property force and back in order to trigger property..

Is there nicer way to accomplish what I do? There is nothing more irritating when power user can't use TAB keys... And I need to get control over focusing in MVVM, this is important for proper data entry flow. But I want code to be somewhat "nice"


It does smell, but I don't think there's anything we can do about it

Usually I do the same thing you have with the AttachedProperty, and keep a single IsFocused bool somewhere in the View (since this is a View-Specific problem, and should not be mixed in with the business logic). I'll then have the View listen to some kind of Event System such as (PRISM's EventAggregator or MVVM Light's Messenger) for ResetFocus events, and I'll raise the ResetFocus event whenever something causes focus to change between my windows/pages, or after a dialog box.

It's not pretty, but it works.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜