代码之家  ›  专栏  ›  技术社区  ›  Charles

WPF-如何将样式应用于AdornedElement占位符的AdornedEelement?

  •  5
  • Charles  · 技术社区  · 17 年前

    我试图将样式应用于装饰元素,但我不知道正确的语法。以下是我尝试过的:

        <!-- ValidationRule Based Validitaion Control Template -->
        <ControlTemplate x:Key="validationTemplate">
            <DockPanel>
                <TextBlock Foreground="Red" FontSize="20">!</TextBlock>
                <AdornedElementPlaceholder Style="textStyleTextBox"/>
            </DockPanel>
        </ControlTemplate>
    

    唯一的问题是以下行不起作用:

                <AdornedElementPlaceholder Style="textStyleTextBox"/>
    

    谢谢,

    1 回复  |  直到 14 年前
        1
  •  9
  •   ΩmegaMan    10 年前

    需要把资源从哪里来。

    <TextBox Style="{StaticResource textStyleTextBox}"/>
    

    然后在资源(如用户控件资源)中定义样式:

    <UserControl.Resources>
      <Style TargetType="TextBox" x:Key="textStyleTextBox">
        <Setter Property="Background" Value="Blue"/>
      </Style>
    </UserControl.Resources>
    

    但是,我不认为你想在占位符中设置装饰元素的样式。它只是该模板中任何控件的占位符。您应该在元素本身中设置装饰元素的样式,就像我上面提供的示例一样。如果你想根据控件的验证来设置控件的样式,那么可以这样做:

    <Window.Resources>
       <ControlTemplate x:Key="validationTemplate">
           <DockPanel>
               <TextBlock Foreground="Yellow" Width="55" FontSize="18">!</TextBlock>
               <AdornedElementPlaceholder/>
           </DockPanel>
       </ControlTemplate>
       <Style x:Key="textBoxInError" TargetType="{x:Type TextBox}">
           <Style.Triggers>
               <Trigger Property="Validation.HasError" Value="true">
                   <Setter Property="Background" Value="Red"/>
                   <Setter Property="Foreground" Value="White"/>
               </Trigger>
           </Style.Triggers>
       </Style>
    </Window.Resources>
    <StackPanel x:Name="mainPanel">
        <TextBlock>Age:</TextBlock>
        <TextBox x:Name="txtAge"
                 Validation.ErrorTemplate="{DynamicResource validationTemplate}"
                 Style="{StaticResource textBoxInError}">
             <Binding Path="Age" UpdateSourceTrigger="PropertyChanged" >
                 <Binding.ValidationRules>
                     <ExceptionValidationRule/>
                 </Binding.ValidationRules>
             </Binding>
        </TextBox> 
    </StackPanel>