0
ListBox
には、ラベルとテキストボックスを含むListBox.ItemTemplate
があります。一部のListBoxアイテムの最初のテキストボックスにフォーカスする
最後の項目の最初のテキストボックスをプログラマチックにフォーカスしたいと思います。どうやってやるの?
データバインディングによって動的に作成されるTextBoxオブジェクトにどうやってアクセスできますかわかりません。
ListBox
には、ラベルとテキストボックスを含むListBox.ItemTemplate
があります。一部のListBoxアイテムの最初のテキストボックスにフォーカスする
最後の項目の最初のテキストボックスをプログラマチックにフォーカスしたいと思います。どうやってやるの?
データバインディングによって動的に作成されるTextBoxオブジェクトにどうやってアクセスできますかわかりません。
この動作を使用してみてください(コードは私のものではありません - 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;
}
}
}