按Meleak對添水壩的答案紙條,這裏是你如何做到這一點的附加的行爲:
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
屬性及其二號TextBox
使用。
+1,在一個側面說明,可以很容易地變成一個附加的行爲的可重用性 –