を、ここにあなたのようにそれを行う方法です添付の行動:
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>
は、第二TextBox
上xmlns:tbb
属性とその使用方法に注意してください。
+1、サイドノートでは、再利用性のために添付の動作に変わる可能性があります。 –