2016-07-06 13 views
0

Ich habe ListBox mit ListBox.ItemTemplate, die einige Beschriftungen und Textfelder enthält.Focus ersten Textfeld in einigen ListBox Artikel

Ich möchte programmatisch ersten Textfeld des letzten Elements konzentrieren. Wie kann ich das machen?

Ich weiß nicht, wie ich auf TextBox-Objekt zugreifen kann, das dynamisch durch Datenbindung erstellt wird.

Antwort

0

Versuchen, dieses Verhalten zu verwenden (Code ist nicht von mir - 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; 
     } 
    } 
}