从视图模型中将焦点设置在 WPF 中的 TextBox 上 [英] Set focus on TextBox in WPF from view model

查看:26
本文介绍了从视图模型中将焦点设置在 WPF 中的 TextBox 上的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的视图中有一个 TextBox 和一个 Button.

I have a TextBox and a Button in my view.

现在我正在检查按钮单击时的条件,如果条件结果为假,则向用户显示消息,然后我必须将光标设置为 TextBox 控件.

Now I am checking a condition upon button click and if the condition turns out to be false, displaying the message to the user, and then I have to set the cursor to the TextBox control.

if (companyref == null)
{
    var cs = new Lipper.Nelson.AdminClient.Main.Views.ContactPanels.CompanyAssociation(); 

    MessageBox.Show("Company does not exist.", "Error", MessageBoxButton.OK,
                    MessageBoxImage.Exclamation);

    cs.txtCompanyID.Focusable = true;

    System.Windows.Input.Keyboard.Focus(cs.txtCompanyID);
}

以上代码在 ViewModel 中.

The above code is in the ViewModel.

CompanyAssociation 是视图名称.

但是光标没有在 TextBox 中设置.

But the cursor is not getting set in the TextBox.

xaml 是:

<igEditors:XamTextEditor Name="txtCompanyID" 
                         KeyDown="xamTextEditorAllowOnlyNumeric_KeyDown"
                         ValueChanged="txtCompanyID_ValueChanged"
                         Text="{Binding Company.CompanyId,
                                        Mode=TwoWay,
                                        UpdateSourceTrigger=PropertyChanged}"
                         Width="{Binding ActualWidth, ElementName=border}"
                         Grid.Column="1" Grid.Row="0"
                         VerticalAlignment="Top"
                         HorizontalAlignment="Stretch"
                         Margin="0,5,0,0"
                         IsEnabled="{Binding Path=IsEditable}"/>

<Button Template="{StaticResource buttonTemp1}"
        Command="{Binding ContactCommand}"
        CommandParameter="searchCompany"
        Content="Search"
        Width="80"
        Grid.Row="0" Grid.Column="2"
        VerticalAlignment="Top"
        Margin="0"
        HorizontalAlignment="Left"
        IsEnabled="{Binding Path=IsEditable}"/>

推荐答案

我分三个部分回答你的问题.

Let me answer to your question in three parts.

  1. 我想知道您的示例中的cs.txtCompanyID"是什么?它是一个文本框控件吗?如果是,那么你走错路了.一般来说,在 ViewModel 中引用 UI 并不是一个好主意.你可以问为什么?"但这是在 Stackoverflow 上发布的另一个问题 :).

  1. I'm wondering what is "cs.txtCompanyID" in your example? Is it a TextBox control? If yes, then you are on a wrong way. Generally speaking it's not a good idea to have any reference to UI in your ViewModel. You can ask "Why?" but this is another question to post on Stackoverflow :).

跟踪 Focus 问题的最佳方法是... 调试 .Net 源代码.不开玩笑.它为我节省了很多时间.要启用 .net 源代码调试,请参阅 Shawn Bruke 的 博客.

The best way to track down issues with Focus is... debugging .Net source code. No kidding. It saved me a lot of time many times. To enable .net source code debugging refer to Shawn Bruke's blog.

最后,我用来从 ViewModel 设置焦点的一般方法是附加属性.我写了非常简单的附加属性,可以在任何 UIElement 上设置.例如,它可以绑定到 ViewModel 的属性IsFocused".这里是:

Finally, general approach that I use to set focus from ViewModel is Attached Properties. I wrote very simple attached property, which can be set on any UIElement. And it can be bound to ViewModel's property "IsFocused" for example. Here it is:

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, 
        DependencyPropertyChangedEventArgs e)
    {
        var uie = (UIElement) d;
        if ((bool) e.NewValue)
        {
            uie.Focus(); // Don't care about false values.
        }
    }
}

现在在您的视图中(在 XAML 中),您可以将此属性绑定到您的 ViewModel:

Now in your View (in XAML) you can bind this property to your ViewModel:

<TextBox local:FocusExtension.IsFocused="{Binding IsUserNameFocused}" />

希望这会有所帮助:).如果它不参考答案#2.

Hope this helps :). If it doesn't refer to the answer #2.

干杯.

这篇关于从视图模型中将焦点设置在 WPF 中的 TextBox 上的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆