-1
通过为TextBox控件定义新的控件模板来创建WPF应用程序。您为TextBox提供自定义外观,并实现在TextBox获得焦点,失去焦点并在文本元素中更改内容(即发生TextChanged事件)时更改外观的功能。WPF中的控件模板
提示:初始状态应该是默认状态(可以选择样式),然后可以在GotFocus和LostFocus事件之间切换。
这是我迄今为止的标记....以及textchanged要求的代码隐藏。当我更改文本块的文本时,Iam无法将背景更改为蓝色。有什么建议么?
<Window x:Class="WpfApplication1.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525">
<Window.Resources>
<ControlTemplate x:Key="myTextBoxTemplate">
<Border
x:Name="templateBorder"
Padding="50" Background="Pink"
BorderBrush="Blue" CornerRadius="5"
BorderThickness="5" HorizontalAlignment="Center">
<TextBlock>
<!--ScrollViewer all the text box to allow entering of text-->
<ScrollViewer Margin="0" x:Name="PART_ContentHost">
</ScrollViewer>
</TextBlock>
</Border>
<ControlTemplate.Triggers>
<Trigger Property="IsEnabled" Value="False">
<Setter TargetName="templateBorder" Property="Background" Value="{StaticResource DisabledBackgroundBrush}"/>
<Setter TargetName="templateBorder" Property="BorderBrush" Value="{StaticResource DisabledBackgroundBrush}"/>
</Trigger>
<Trigger Property="IsMouseOver" Value="True">
<Setter TargetName="templateBorder" Property="BorderThickness" Value="8"/>
</Trigger>
<Trigger Property="IsKeyboardFocused" Value="True">
<Setter TargetName="templateBorder" Property="Background" Value="Red"/>
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Window.Resources>
<StackPanel>
<TextBox Text="Click Me" FontWeight="Bold" Template="{StaticResource myTextBoxTemplate}"
Name="myTextBox" TextChanged="myTextBox_TextChanged" Opacity="1"/>
</StackPanel>
</Window>
方法:
private void myTextBox_TextChanged(object sender, TextChangedEventArgs e)
{
myTextBox.Background = Brushes.Blue;
}