WPF Style Trigger

索引サイト表示




<Grid.Resources>
<Style TargetType="{x:Type TextBox}">
<Style.Triggers>
<Trigger Property="IsFocused" Value="True">
<Setter Property="Background" Value="Cyan"/>
</Trigger>
</Style.Triggers>
</Style>
</Grid.Resources>

<Button Content="Button" Grid.Column="1" Margin="5" Name="button1" Click="button1_Click" />

<TextBox Grid.Column="2" Grid.Row="1" Margin="5" Name="textBox21" Text="TextBox21" />
<TextBox Grid.Column="2" Grid.Row="2" Margin="5" Name="textBox22" Text="TextBox22" />
<TextBox Grid.Column="2" Grid.Row="3" Margin="5" Name="textBox23" Text="TextBox23" />
<TextBox Grid.Column="2" Grid.Row="4" Margin="5" Name="textBox24" Text="TextBox24" />
<TextBox Grid.Column="2" Grid.Row="5" Margin="5" Name="textBox25" Text="TextBox25" />

<TextBox Grid.Column="3" Grid.Row="1" Margin="5" Text="TextBox" Tag="1" KeyDown="TextBox_KeyDown" />
<TextBox Grid.Column="3" Grid.Row="2" Margin="5" Text="TextBox" Tag="2" KeyDown="TextBox_KeyDown" />
<TextBox Grid.Column="3" Grid.Row="3" Margin="5" Text="TextBox" Tag="3" KeyDown="TextBox_KeyDown" />
<TextBox Grid.Column="3" Grid.Row="4" Margin="5" Text="TextBox" Tag="4" KeyDown="TextBox_KeyDown" />
<TextBox Grid.Column="3" Grid.Row="5" Margin="5" Text="TextBox" Tag="5" KeyDown="TextBox_KeyDown" />

<Label Content="Label" Grid.Column="3" Grid.Row="6" Margin="5"
Name="label1" FontSize="24" HorizontalAlignment="Center" VerticalAlignment="Center" />




TextBox[] z_text = new TextBox[9];

private void button1_Click(object sender, RoutedEventArgs e)
{
Style z_style = new Style(typeof(TextBox));

Trigger z_trigger = new Trigger();
z_trigger.Property = TextBox.IsFocusedProperty;
z_trigger.Value = true;
z_trigger.Setters.Add(new Setter(Control.BackgroundProperty,Brushes.Gold));
z_style.Triggers.Add(z_trigger);

for (int idx = 1; idx < 6; idx++)
{
z_text[idx] = new TextBox();
z_text[idx].Name = "texBox1" + idx;

z_text[idx].SetValue(Grid.ColumnProperty, 1);
z_text[idx].SetValue(Grid.RowProperty, idx);
z_text[idx].SetValue(Grid.MarginProperty, new Thickness(5));

z_text[idx].Resources.Add(typeof(TextBox),z_style);
z_text[idx].Text = z_text[idx].Name;
z_text[idx].LostFocus += new RoutedEventHandler(TextBox_LostFocus);

Grid1.Children.Add(z_text[idx]);
}
}




private void TextBox_KeyDown(object sender, KeyEventArgs e)
{
int idx = 0;
TextBox z_textbox = (TextBox)e.Source;
idx = Convert.ToInt16( z_textbox.Tag);
label1.Content = idx;

if ((Keyboard.Modifiers == ModifierKeys.None) && (e.Key == Key.Enter))
{
UIElement element = sender as UIElement;
element.MoveFocus(new TraversalRequest(FocusNavigationDirection.Next));
}

if ((Keyboard.Modifiers == ModifierKeys.Shift) && (e.Key == Key.Enter))
{
UIElement element = sender as UIElement;
element.MoveFocus(new TraversalRequest(FocusNavigationDirection.Previous));
}
}



AX