2017-06-14 43 views
1

我有一個包含許多文本框的窗體,每個窗體都需要相同的驗證錯誤模板。 現在,我不想爲每個文本框寫這些驗證錯誤模板。那麼我必須把它放在哪裏,以便所有的文本框都受到影響?WPF - 用於應用程序中所有文本框的自定義ErrorTemplate

文本框與Validation.ErrorTemplate:

<TextBox x:Name="textBox3" TextWrapping="Wrap" Height="23" Text="{Binding User_Id, UpdateSourceTrigger=PropertyChanged, NotifyOnValidationError=True}" VerticalAlignment="Top"> 
<Validation.ErrorTemplate> 
    <ControlTemplate> 
    <StackPanel> 
     <AdornedElementPlaceholder x:Name="textBox"/> 
     <ItemsControl ItemsSource="{Binding}"> 
     <ItemsControl.ItemTemplate> 
      <DataTemplate> 
      <TextBlock Text="{Binding ErrorContent}" Foreground="Red"/> 
      </DataTemplate> 
     </ItemsControl.ItemTemplate> 
     </ItemsControl> 
    </StackPanel> 
    </ControlTemplate> 
</Validation.ErrorTemplate> 
</TextBox> 

我CustomControl:

public class ValidationTextBox : TextBox 
    { 
     static ValidationTextBox() 
     { 
      DefaultStyleKeyProperty.OverrideMetadata(typeof(ValidationTextBox), new FrameworkPropertyMetadata(typeof(ValidationTextBox))); 
      //Validation.SetErrorTemplate(new ValidationTextBox(),) 
     } 
     public ValidationTextBox() { } 
    } 

回答

2

您需要定義新樣式的文本框文本框的容器的 「國土資源」 標籤內。此樣式將針對容器內的每個文本框實施。

例子:

<StackPanel> 
<StackPanel.Resources> 
<Style TargetType=TextBox> 
<Setter Property="Validation.ErrorTemplate"> 
<Setter.Value> 
<ControlTemplate> 
    <StackPanel> 
     <AdornedElementPlaceholder x:Name="textBox"/> 
     <ItemsControl ItemsSource="{Binding}"> 
     <ItemsControl.ItemTemplate> 
      <DataTemplate> 
      <TextBlock Text="{Binding ErrorContent}" Foreground="Red"/> 
      </DataTemplate> 
     </ItemsControl.ItemTemplate> 
     </ItemsControl> 
    </StackPanel> 
    </ControlTemplate> 
</Setter.Value> 
</Setter> 
</Style> 
</StackPanel.Resources 
<TextBox/> 
<TextBox/> 
<TextBox/> 
</StackPanel> 
+0

我把它放在我的App.xaml(Application.Ressources)。這工作,謝謝! :)自定義控件不需要。 – lordnik22

相關問題