【问题标题】:Set Focus in VisualStatemanager在 VisualStatemanager 中设置焦点
【发布时间】:2016-03-26 14:43:03
【问题描述】:

我编写了一个自定义控件并希望将焦点设置在控件上,以防 VisualState 处于活动状态。

该控件是一种 ComboBox,在下拉弹出窗口中有一个搜索框。当我打开它时,Opened 视觉状态会激活,并且搜索框应该是焦点。除了依赖属性bool IsDropDownOpen 将是true。

PS:这是一个 Windows 10 UWP 项目。

【问题讨论】:

    标签: c# xaml winrt-xaml win-universal-app


    【解决方案1】:

    抱歉,您只能以编程方式设置焦点,而不能通过视觉状态设置焦点:(

    【讨论】:

    • 这很烦人。你知道是否可以在 UWP 中创建自定义动画吗?我可以从 TimeLine 或 ObjectKeyFrame 派生,但在 WPF 中没有像 GetCurrentValue 这样的值的动画。
    • 抱歉,我从来没有尝试过 WPF...你想要什么动画?
    • 在 WPF 中,您可以创建自定义动画。因此,您可以在特定时间将焦点设置到给定控件。但我不知道在UWP中是否也可以。
    • @Koopakiller,不,你不能在 UWP 中创建自定义动画。关于 UWP 中动画的所有内容,您可以找到 here
    【解决方案2】:

    不是我最喜欢的解决方案,而是一种无需从后面的代码访问 TextBox 的解决方法。

    我实现了一个附加属性,它将焦点设置为控件,以防属性设置为true。

    public class FocusHelper : DependencyObject
    {
        #region Attached Properties
    
        public static readonly DependencyProperty IsFocusedProperty = DependencyProperty.RegisterAttached("IsFocused", typeof(bool), typeof(FocusHelper), new PropertyMetadata(default(bool), OnIsFocusedChanged));
    
        public static bool GetIsFocused(DependencyObject obj)
        {
            return (bool)obj.GetValue(IsFocusedProperty);
        }
    
        public static void SetIsFocused(DependencyObject obj, bool value)
        {
            obj.SetValue(IsFocusedProperty, value);
        }
    
        #endregion
    
        #region Methods
    
        public static void OnIsFocusedChanged(DependencyObject s, DependencyPropertyChangedEventArgs e)
        {
            var ctrl = s as Control;
            if (ctrl == null)
            {
                throw new ArgumentException();
            }
    
            if ((bool)e.NewValue)
            {
                ctrl.Focus(FocusState.Keyboard);
            }
        }
    
        #endregion
    }
    

    所以我可以将此属性绑定到我的IsDropDownOpen 属性。所以每次我打开下拉菜单时,TextBox 都会获得焦点。

    <TextBox helper:FocusHelper.IsFocused="{Binding IsDropDownOpen, RelativeSource={RelativeSource TemplatedParent}, Mode=OneWay}" ...
    

    【讨论】:

      猜你喜欢
      • 2010-10-05
      • 1970-01-01
      • 1970-01-01
      • 2010-10-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-06-25
      • 2011-09-09
      相关资源
      最近更新 更多