2016-07-06 64 views
0

我有ListBoxListBox.ItemTemplate,它包含一些標籤和文本框。將某個列表框項目中的第一個文本框對焦

我想以編程方式聚焦上一個項目的第一個文本框。我怎樣才能做到這一點?

我不知道如何訪問由數據綁定動態創建的TextBox對象。

回答

0

嘗試使用此行爲(代碼是不是我 - https://gist.github.com/tswann/892163

using System; 
using System.Windows; 

namespace MyProject.WPF.Helpers 
{ 
    /// <summary> 
    /// Allows an arbitrary UI element to bind keyboard focus to an attached property. 
    /// </summary> 
    public static class FocusBehaviour 
    { 
     public static bool GetHasKeyboardFocus(DependencyObject obj) 
     { 
      return (bool)obj.GetValue(HasKeyboardFocusProperty); 
     } 

     public static void SetHasKeyboardFocus(DependencyObject obj, bool value) 
     { 
      obj.SetValue(HasKeyboardFocusProperty, value); 
     } 

     // Using a DependencyProperty as the backing store for HasKeyboardFocus. This enables animation, styling, binding, etc... 
     public static readonly DependencyProperty HasKeyboardFocusProperty = 
      DependencyProperty.RegisterAttached("HasKeyboardFocus", 
      typeof(bool), 
      typeof(FocusBehaviour), 
      new UIPropertyMetadata(false, null, CoerceCurrentValue)); 

     /// <summary> 
     /// Coerce property value and give focus to bound control if true. 
     /// </summary> 
     /// <param name="source">UIElement to which this property has been attached.</param> 
     /// <param name="value">Property value</param> 
     /// <returns>Property value</returns> 
     private static object CoerceCurrentValue(DependencyObject source, object value) 
     { 
      UIElement control = source as UIElement; 
      if (control != null) 
      { 
       bool hasFocus = (bool)value; 

       if (hasFocus) 
       { 
        System.Threading.ThreadPool.QueueUserWorkItem((a) => 
        { 
         control.Dispatcher.Invoke(new Action(() => 
         { 
          control.Focus(); 
         })); 
        }); 
       } 
      } 

      return value; 
     } 
    } 
} 
相關問題