WPF / XAML:用户控件的快捷方式

时间:2014-01-09 08:10:27

标签: wpf xaml user-controls label keyboard-shortcuts

我创建了一个名为ContactPerson的UserControl。它包含人名,电话号码等。

此用户控件没有标题(例如“_Contact Person”之类的标签),因为我在不同情况下使用此用户控件。

但在某种情况下,我确实有这样的标签,这意味着我的代码看起来有点像这样:

<Label Content="_Contact Person" 
       Target="{Binding ElementName=_contactView}" />


<View1:contactView x:Name="_contactView" 
                   DataContext="{Binding SupplierContact}"/>

我想 - 将键盘焦点设置到ContactPersonUserControl中的name-textbox,但这似乎是一项艰巨的任务(在alle之后它是私有的)。

我不想在usercontrol中移动标签,我想这实际上是最简单的解决方案。在我看来,XAML应该为这种情况提供解决方案。

如何以简单而优雅的方式做到这一点?

THX

(我有一些这些控件,所以我需要多次使用相同的解决方案)。

2 个答案:

答案 0 :(得分:0)

我不确定我是否正确了解您的场景,但如果您想从视图模型将焦点设置为ui控件,则可能需要创建附加属性。

附属财产:

 public static class ControlFocusExtension
    {
        public static readonly DependencyProperty IsFocusedProperty = DependencyProperty.RegisterAttached("IsFocused", typeof(bool), typeof(ControlFocusExtension), new UIPropertyMetadata(false, OnIsFocusedPropertyChanged));

        public static bool GetIsFocused(DependencyObject obj)
        {
            return (bool)obj.GetValue(IsFocusedProperty);
        }

        public static void SetIsFocused(DependencyObject obj, bool value)
        {
            obj.SetValue(IsFocusedProperty, value);
        }



        private static void OnIsFocusedPropertyChanged(DependencyObject pDependencyObject, DependencyPropertyChangedEventArgs e)
        {
            var uie = (UIElement)pDependencyObject;
            if ((bool)e.NewValue)
            {
                uie.Focus(); 
            }
        }
    }

用户控制XAML:

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

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

如果需要,您可以在视图模型中更改 IsNameFocused 的值。

或者,如果您不想绑定它,那么您可以将其用作 -

<TextBox local:FocusExtension.IsFocused="True" /> 

答案 1 :(得分:0)

将focusvisualstyle属性设置为null,以便您不想像这样设置焦点

示例<Label FocusVisualStyle="{x:Null}">

和文本框焦点<TextBox Focusable="True"/>