将第一个文本框放在某个ListBox项

时间:2016-07-06 10:07:37

标签: wpf listbox itemtemplate

我的ListBox ListBox.ItemTemplate包含一些标签和文本框。

我想以编程方式聚焦最后一项的第一个文本框。我怎么能这样做?

我不知道如何访问由数据绑定动态创建的TextBox对象。

1 个答案:

答案 0 :(得分: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;
        }
    }
}