2009-04-01 17 views
4

飾った要素にスタイルを適用しようとしていますが、正しい構文がわかりません。ここで私が試したものです:WPF - AdornedElementPlaceholderのAdornedElementにスタイルを適用する方法

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

唯一の問題は次の行が動作しないということである。

  <AdornedElementPlaceholder Style="textStyleTextBox"/> 

すべてのヘルプはなり大変感謝します。

おかげで、

-Charles

答えて

9

は、リソースがどこから来ている配置する必要があります。

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

次に、このようなユーザーコントロールのリソースなどのリソースにスタイルを定義します。

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

私はあなたが、プレースホルダ内adornedelementのスタイルを設定したいと考えているいけないが。このテンプレートを使用するコントロールのプレースホルダです。上記の例のように、要素自体の装飾要素のスタイルを設定する必要があります。それに基づいてコントロールのスタイルを設定する場合は、次のようなものを入力します。

<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> 
+0

ありがとうございます。検証が必要なすべてのテキストボックスで 'Validation.ErrorTemplate'と 'Style'の両方を設定するのではなく、エラーが発生したときに 'textStyleTextBox'を使用することをControlTemplateに記述する方法があることを期待していました。あなたはそれをするために何らかの方法を考えることができますか? – Charles

+1

アプリケーションレベル(Application.Resources)でスタイルを使用するには、テキストブロックスタイルなどのキーを使用せず、すべてのテキストブロックが自動的にそのスタイルを自動的に選択します。 – Crippeoblade

+0

通常のテキストボックスから派生した独自のテキストボックスを作成するのはどうですか?デフォルトではスタイルとエラーの検証をここで定義します。その後、他のXamlファイルでは通常どおりにカスタムテキストボックスを使用します。 – Crippeoblade

関連する問題