-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;
}