我想在我的所有TextBox控件上设置一个样式,它在接收键盘焦点时执行以下操作:
1)更改背景颜色
2)调用.SelectAll()突出显示所有文本
到目前为止,我有这个:
<Style TargetType="TextBox">
<Style.Triggers>
<Trigger Property="IsKeyboardFocusWithin" Value="True">
<Setter Property="Background">
<Setter.Value>
<SolidColorBrush Color="#FFFFD1D9"/>
</Setter.Value>
</Setter>
</Trigger>
</Style.Triggers>
</Style>
还有办法打电话给.SelectAll()
吗?感谢。
答案 0 :(得分:20)
您可以使用附加行为执行此操作。
示例强>
public static class TextBoxBehaviour
{
public static bool GetSelectAll(TextBoxBase target)
{
return (bool)target.GetValue(SelectAllAttachedProperty);
}
public static void SetSelectAll(TextBoxBase target, bool value)
{
target.SetValue(SelectAllAttachedProperty, value);
}
public static readonly DependencyProperty SelectAllAttachedProperty = DependencyProperty.RegisterAttached("SelectAll", typeof(bool), typeof(TextBoxBehaviour), new UIPropertyMetadata(false, OnSelectAllAttachedPropertyChanged));
static void OnSelectAllAttachedPropertyChanged(DependencyObject o, DependencyPropertyChangedEventArgs e)
{
((TextBoxBase)o).SelectAll();
}
}
<强>用法强>
<Style TargetType="{x:Type TextBox}" xmlns:behaviours="clr-namespace:Controls.Behaviours">
<Style.Triggers>
<Trigger Property="IsKeyboardFocusWithin" Value="True">
<Setter Property="Background" Value="#FFFFD1D9"/>
<Setter Property="behaviours:TextBoxBehaviour.SelectAll" Value="True"/>
</Trigger>
</Style.Triggers>
</Style>
参考文献
注意:在理论上无法测试上述实现,尽管它应该只是工作™。
HTH,