【问题标题】:Apply style to multiple controls when a style trigger fires in xaml当样式触发器在 xaml 中触发时,将样式应用于多个控件
【发布时间】:2012-04-10 07:52:40
【问题描述】:

当用户输入信息时,我希望所有控件的外观和行为方式都相同,因此我完成了以下操作。

标签和文本框控件位于堆栈面板中:

    <StackPanel Style="{StaticResource ResourceKey=myInput}" HorizontalAlignment="Left">
        <Label Content="Label" Name="label1"  />
        <TextBox Name="textBox1"  ></TextBox>
    </StackPanel>

样式“myInput”是:

<Style x:Key="myInput" TargetType="{x:Type StackPanel}">
    <Style.Resources>
            <Style TargetType="{x:Type Label}" BasedOn="{StaticResource {x:Type Label}}">
                <Setter Property="FontSize" Value="12" />
            </Style>
            <Style TargetType="{x:Type TextBox}">
                <Setter Property="Margin" Value="5,-5,2,2"></Setter>
                <Setter Property="Height" Value="23"/>
                <Setter Property="VerticalAlignment" Value="Top"/>
                <Style.Triggers>
                    <Trigger Property="IsFocused" Value="true">
                        <Setter Property="Background" Value="Blue" >                                
                        </Setter>                           
                    </Trigger>
                </Style.Triggers>
            </Style>
    </Style.Resources>
</Style>

现在,每次我将该样式应用于具有标签和文本框的堆栈面板时,文本框的背景都会在获得焦点时变为蓝色。

当该事件触发时,我如何将标签的字体粗细也设置为粗体?我想用 xaml 来做到这一点。

【问题讨论】:

  • 您是否正在寻找通过 xaml 设置粗体字重?像这样:。或者你想在活动中实现风格改变?
  • 我想在文本框获得焦点时这样做。所以是的,我想改变事件的风格。标签将始终是文本框的兄弟,也许我可以使用某种相对绑定。

标签: wpf xaml styles


【解决方案1】:

在您的Label 上使用DataTrigger,以查看键盘焦点是否在包含两个对象的父StackPanel

<Style TargetType="{x:Type Label}" BasedOn="{StaticResource {x:Type Label}}">
    <Setter Property="FontSize" Value="12" />
    <Style.Triggers>
        <DataTrigger Value="True" Binding="{Binding IsKeyboardFocusWithin,
            RelativeSource={RelativeSource AncestorType={x:Type StackPanel}}}">
            <Setter Property="FontWeight" Value="Bold" />
        </Trigger>
    </Style.Triggers>
</Style>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-03-26
    • 1970-01-01
    • 2010-10-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-07
    相关资源
    最近更新 更多