Решение по вопросам тем TextBox запретить изменение цвета BorderBrush, Убрать рамочку вокруг textbox
Вопрос в том, как поменять цвет рамки или убрать рамку TextBox при фокусировке. В невыделанном состоянии для рамки используется кисть из свойства TextBox.BorderBrush. Но при выделении (Focus или MouseOver) используемые кисти недоступны.
Есть несколько способов решения этого вопроса. В основном предлагается переопределение шаблона с использование триггеров.
Я предлагаю внесением изменений в дефолтный шаблон сделать доступными для изменения кисти для рамок.
Рассмотрим дефолтный шаблон TextBox
Кликните здесь для просмотра всего текста
XML | 1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
| <Window.Resources>
<SolidColorBrush x:Key="TextBox.Static.Border" Color="#FFABAdB3"/>
<SolidColorBrush x:Key="TextBox.MouseOver.Border" Color="#FF7EB4EA"/>
<SolidColorBrush x:Key="TextBox.Focus.Border" Color="#FF569DE5"/>
<Style TargetType="{x:Type TextBox}">
<Setter Property="Background" Value="{DynamicResource {x:Static SystemColors.WindowBrushKey}}"/>
<Setter Property="BorderBrush" Value="{StaticResource TextBox.Static.Border}"/>
<Setter Property="Foreground" Value="{DynamicResource {x:Static SystemColors.ControlTextBrushKey}}"/>
<Setter Property="BorderThickness" Value="1"/>
<Setter Property="KeyboardNavigation.TabNavigation" Value="None"/>
<Setter Property="HorizontalContentAlignment" Value="Left"/>
<Setter Property="FocusVisualStyle" Value="{x:Null}"/>
<Setter Property="AllowDrop" Value="true"/>
<Setter Property="ScrollViewer.PanningMode" Value="VerticalFirst"/>
<Setter Property="Stylus.IsFlicksEnabled" Value="False"/>
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type TextBox}">
<Border x:Name="border" BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="{TemplateBinding BorderThickness}" Background="{TemplateBinding Background}" SnapsToDevicePixels="True">
<ScrollViewer x:Name="PART_ContentHost" Focusable="false" HorizontalScrollBarVisibility="Hidden" VerticalScrollBarVisibility="Hidden"/>
</Border>
<ControlTemplate.Triggers>
<Trigger Property="IsEnabled" Value="false">
<Setter Property="Opacity" TargetName="border" Value="0.56"/>
</Trigger>
<Trigger Property="IsMouseOver" Value="true">
<Setter Property="BorderBrush" TargetName="border" Value="{StaticResource TextBox.MouseOver.Border}"/>
</Trigger>
<Trigger Property="IsKeyboardFocused" Value="true">
<Setter Property="BorderBrush" TargetName="border" Value="{StaticResource TextBox.Focus.Border}"/>
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Setter.Value>
</Setter>
<Style.Triggers>
<MultiTrigger>
<MultiTrigger.Conditions>
<Condition Property="IsInactiveSelectionHighlightEnabled" Value="true"/>
<Condition Property="IsSelectionActive" Value="false"/>
</MultiTrigger.Conditions>
<Setter Property="SelectionBrush" Value="{DynamicResource {x:Static SystemColors.InactiveSelectionHighlightBrushKey}}"/>
</MultiTrigger>
</Style.Triggers>
</Style>
</Window.Resources> |
|
Рамку при наведении мыши определяют теги 26-28 строк, клавиатуры - строки 29-31. Цвет рамки для мыши определяет ресурс TextBox.MouseOver.Border, клавиатуры - TextBox.Focus.Border. Обе привязки к ресурсу статические - то есть, после инициализации шаблона их изменить нельзя.
Что бы стало возможно в определении TextBox менять эти ресурсы, изменим привязки на динамическиеXML | 26
27
28
29
30
31
| <Trigger Property="IsMouseOver" Value="true">
<Setter Property="BorderBrush" TargetName="border" Value="{DynamicResource TextBox.MouseOver.Border}"/>
</Trigger>
<Trigger Property="IsKeyboardFocused" Value="true">
<Setter Property="BorderBrush" TargetName="border" Value="{DynamicResource TextBox.Focus.Border}"/>
</Trigger> |
|
Теперь мы можем устанавливать цвет рамки для любого режима. Если какая-то рамка не нужна, надо установить её цвет "Transparent". В примере устанавливаются цвета: для обычного состояния - Green, при наведении мыши - Red, при клавиатурном фокусе - YellowXML | 1
2
3
4
5
6
| <TextBox VerticalAlignment="Center" HorizontalAlignment="Center" BorderBrush="Green" Text="Пример текста">
<TextBox.Resources>
<SolidColorBrush x:Key="TextBox.MouseOver.Border" Color="Red"/>
<SolidColorBrush x:Key="TextBox.Focus.Border" Color="Yellow"/>
</TextBox.Resources>
</TextBox> |
|
Сам переопределённый шаблон и сопутствующие ресурсы лучше прописать в словаре, чтобы не загромождать Xaml окна. Словарь, в зависимости от необходимости, подключить на уровне окна или приложения.
Ниже полный Xaml примера с определением шаблона в ресурсах окна и двумя TextBox - один без рамок.XML | 1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
| <Window x:Class="Cs_WPF.TextBoxTemplate__1513854_2351583_"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:Cs_WPF"
mc:Ignorable="d"
Title="TextBoxTemplate__1513854_2351583_" Height="204" Width="371" FontSize="20">
<Window.Resources>
<SolidColorBrush x:Key="TextBox.Static.Border" Color="#FFABAdB3"/>
<SolidColorBrush x:Key="TextBox.MouseOver.Border" Color="#FF7EB4EA"/>
<SolidColorBrush x:Key="TextBox.Focus.Border" Color="#FF569DE5"/>
<Style TargetType="{x:Type TextBox}">
<Setter Property="Background" Value="{DynamicResource {x:Static SystemColors.WindowBrushKey}}"/>
<Setter Property="BorderBrush" Value="{StaticResource TextBox.Static.Border}"/>
<Setter Property="Foreground" Value="{DynamicResource {x:Static SystemColors.ControlTextBrushKey}}"/>
<Setter Property="BorderThickness" Value="1"/>
<Setter Property="KeyboardNavigation.TabNavigation" Value="None"/>
<Setter Property="HorizontalContentAlignment" Value="Left"/>
<Setter Property="FocusVisualStyle" Value="{x:Null}"/>
<Setter Property="AllowDrop" Value="true"/>
<Setter Property="ScrollViewer.PanningMode" Value="VerticalFirst"/>
<Setter Property="Stylus.IsFlicksEnabled" Value="False"/>
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type TextBox}">
<Border x:Name="border" BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="{TemplateBinding BorderThickness}" Background="{TemplateBinding Background}" SnapsToDevicePixels="True">
<ScrollViewer x:Name="PART_ContentHost" Focusable="false" HorizontalScrollBarVisibility="Hidden" VerticalScrollBarVisibility="Hidden"/>
</Border>
<ControlTemplate.Triggers>
<Trigger Property="IsEnabled" Value="false">
<Setter Property="Opacity" TargetName="border" Value="0.56"/>
</Trigger>
<Trigger Property="IsMouseOver" Value="true">
<Setter Property="BorderBrush" TargetName="border" Value="{DynamicResource TextBox.MouseOver.Border}"/>
</Trigger>
<Trigger Property="IsKeyboardFocused" Value="true">
<Setter Property="BorderBrush" TargetName="border" Value="{DynamicResource TextBox.Focus.Border}"/>
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Setter.Value>
</Setter>
<Style.Triggers>
<MultiTrigger>
<MultiTrigger.Conditions>
<Condition Property="IsInactiveSelectionHighlightEnabled" Value="true"/>
<Condition Property="IsSelectionActive" Value="false"/>
</MultiTrigger.Conditions>
<Setter Property="SelectionBrush" Value="{DynamicResource {x:Static SystemColors.InactiveSelectionHighlightBrushKey}}"/>
</MultiTrigger>
</Style.Triggers>
</Style>
</Window.Resources>
<Grid>
<TextBox VerticalAlignment="Top" HorizontalAlignment="Center" BorderBrush="Green" Text="Пример текста">
<TextBox.Resources>
<SolidColorBrush x:Key="TextBox.MouseOver.Border" Color="Red"/>
<SolidColorBrush x:Key="TextBox.Focus.Border" Color="Yellow"/>
</TextBox.Resources>
</TextBox>
<TextBox VerticalAlignment="Center" HorizontalAlignment="Center" BorderBrush="Transparent" Text="Пример текста">
<TextBox.Resources>
<SolidColorBrush x:Key="TextBox.MouseOver.Border" Color="Transparent"/>
<SolidColorBrush x:Key="TextBox.Focus.Border" Color="Transparent"/>
</TextBox.Resources>
</TextBox>
<Button VerticalAlignment="Bottom" HorizontalAlignment="Center">Кнопка</Button>
</Grid>
</Window> |
|
|