【问题标题】:WPF/XAML: Shortcut to a user controlWPF/XAML:用户控件的快捷方式
【发布时间】:2014-01-09 08:10:26
【问题描述】:

我创建了一个名为 ContactPerson 的用户控件。它包含人名、电话号码等。

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

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

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


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

我想 - 将键盘焦点设置为 ContactPersonUserControl 内的名称文本框,但这似乎是一项艰巨的任务(毕竟它是私有的)。

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

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

谢谢

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

【问题讨论】:

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


    【解决方案1】:

    我不确定我是否正确理解了您的场景,但是如果您想从视图模型将焦点设置为 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 的值。

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

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

    【讨论】:

      【解决方案2】:

      为那些你不想像这样设置焦点的人设置 focusvisualstyle 属性为 null

      示例&lt;Label FocusVisualStyle="{x:Null}"&gt;

      对于文本框焦点&lt;TextBox Focusable="True"/&gt;

      【讨论】:

        猜你喜欢
        • 2011-08-26
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-04-15
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多