В соответствии с примечанием Милика к ответу Тима Дамса, вот как вы делаете это как прикрепленное поведение:
using System.Windows;
using System.Windows.Controls;
public static class TextBoxBehavior
{
public static bool GetHomeOnLostFocus(DependencyObject obj)
{
return (bool)obj.GetValue(HomeOnLostFocusProperty);
}
public static void SetHomeOnLostFocus(DependencyObject obj, bool value)
{
obj.SetValue(HomeOnLostFocusProperty, value);
}
// Using a DependencyProperty as the backing store for HomeOnLostFocus.
// This enables animation, styling, binding, etc...
public static readonly DependencyProperty HomeOnLostFocusProperty =
DependencyProperty.RegisterAttached(
"HomeOnLostFocus",
typeof(bool),
typeof(TextBoxBehavior),
new UIPropertyMetadata(false, OnHomeOnLostFocusChanged));
public static void OnHomeOnLostFocusChanged(
DependencyObject d,
DependencyPropertyChangedEventArgs e)
{
// Type checking and casting of parameters
bool oldVal = (bool)e.OldValue;
bool newVal = (bool)e.NewValue;
TextBox textBox = d as TextBox;
// Argument value tests
if (textBox == null) return;
if (oldVal == newVal) return;
// If HomeOnLostFocus then add event handler, otherwise, remove it.
if (newVal)
textBox.LostFocus += TextBox_LostFocus;
else
textBox.LostFocus -= TextBox_LostFocus;
}
static void TextBox_LostFocus(object sender, RoutedEventArgs e)
{
var textBox = (TextBox)sender;
textBox.SelectionStart = 0;
}
}
Нужны ссылки на сборки PresentationCore
, PresentationFramework
, System.Xaml
и WindowsBase
.
Вот пример использования:
<Window x:Class="WpfApplication1.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:tbb="clr-namespace:TextBoxBehavior;assembly=TextBoxBehavior"
Title="MainWindow" Height="350" Width="525">
<StackPanel>
<TextBox Width="200"/>
<TextBox tbb:TextBoxBehavior.HomeOnLostFocus="true" Width="200"/>
<Button Content="Dummy" Width="200"/>
</StackPanel>
</Window>
Обратите внимание на атрибут xmlns:tbb
и его использование на 2-м TextBox
.