TextBox コントロールの新しいコントロール テンプレートを定義して、WPF アプリケーションを作成します。TextBox にカスタムの外観を提供し、TextBox がフォーカスを取得したとき、フォーカスを失ったとき、およびテキスト要素のコンテンツが変更されたとき (つまり、TextChanged イベントが発生したとき) にその外観を変更する機能を実装します。
ヒント: 初期状態は (スタイルを選択した) デフォルト状態である必要があります。その後、GotFocus イベントと LostFocus イベントを切り替えることができます。
これは私がこれまでに持っているマークアップです.... textchanged 要件のコード ビハインドと一緒です。テキストブロックのテキストを変更すると、背景を青に変更できません。助言がありますか?
<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;
}