WPF网格:设置焦点行的样式

时间:2014-03-18 17:32:44

标签: c# wpf xaml

我有一个简单的WPF网格作为示例,每行具有相同的高度(*)。三行中的每一行都有一个文本框。我想知道在XAML中是否可以指定当文本框获得焦点时,相关行应该增加到2 *(从而增加文本框的大小)。

...谢谢

-Ben

 <Window x:Class="WpfApplication2.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">

   <Grid>
      <Grid.RowDefinitions>
         <RowDefinition Height="*" />
         <RowDefinition Height="*" />
         <RowDefinition Height="*" />
      </Grid.RowDefinitions>
      <TextBox Background="AliceBlue" Grid.Row="0" />
      <TextBox Background="AliceBlue" Grid.Row="1" />
      <TextBox Background="AliceBlue" Grid.Row="2" />
   </Grid>
 </Window>

2 个答案:

答案 0 :(得分:0)

您可以使用Grid.Row设置Trigger的样式值,如下所示:

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

但要将Grid中的所有元素放在本地设置Grid.Row的值所需。在这种情况下,给定我们在Style值中的Dependency Property Value Precedence将被忽略。

我建议您只为Height设置TextBox,如下所示:

<Window.Resources>
    <Style TargetType="{x:Type TextBox}">
        <Setter Property="Height" Value="100" />
        <Setter Property="Background" Value="AliceBlue" />

        <Style.Triggers>
            <Trigger Property="IsFocused" Value="True">
                <Setter Property="Height" Value="200" />
                <Setter Property="Background" Value="Beige" />
            </Trigger>
        </Style.Triggers>
    </Style>
</Window.Resources>

<Grid>
    <Grid.RowDefinitions>
        <RowDefinition Height="*" />
        <RowDefinition Height="*" />
        <RowDefinition Height="*" />
    </Grid.RowDefinitions>

    <TextBox Name="TextBox1" Grid.Row="0" /> 
    <TextBox Name="TextBox2" Grid.Row="1" />
    <TextBox Name="TextBox3" Grid.Row="2" /> 
</Grid>

或者根据焦点通过EventTriggers隐藏/显示TextBox。为此,您只需为每个TextBox创建EventTriggerGotFocusLostFocus个事件。有关详细信息,请参阅:

MSDN: EventTrigger

答案 1 :(得分:0)

您是否只是在任何文本块获得焦点时尝试使字体更大?如果是,那么这是一种方法

<Window.Resources>
    <Style TargetType="TextBox">
        <Style.Triggers>
            <Trigger Property="IsFocused" Value="True">
                <Setter Property="FontSize" Value="20"/>
            </Trigger>
        </Style.Triggers>
    </Style>
</Window.Resources>

<Grid>
    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition Height="*" />
            <RowDefinition Height="*" />
            <RowDefinition Height="*" />
        </Grid.RowDefinitions>

        <TextBox Background="AliceBlue" Grid.Row="0" />
        <TextBox Background="AliceBlue" Grid.Row="1" />
        <TextBox Background="AliceBlue" Grid.Row="2" />
    </Grid>
</Grid>