你可以做的是創建一個模板化控件(你可以很容易地創建一個通過視覺工作室添加 - 新項菜單)whcich你從Control派生:
public class MyListBox : ListBox
{
public MyListBox()
{
this.DefaultStyleKey = typeof(MyListBox);
}
}
當你創建一個模板控制它會也創建文件夾主題,並在那裏定義了樣式的generic.xaml。 之後採取的列表框 - 從here樣式複製並粘貼到你的generic.xaml在正確的位置(您需要的ValidationTooltipTemplate,太):
<Style TargetType="local:MyListBox">
<Setter Property="Padding" Value="1"/>
<Setter Property="Background" Value="#FFFFFFFF" />
<Setter Property="Foreground" Value="#FF000000"/>
<Setter Property="HorizontalContentAlignment" Value="Left" />
<Setter Property="VerticalContentAlignment" Value="Top" />
<Setter Property="IsTabStop" Value="False" />
<Setter Property="BorderThickness" Value="1" />
<Setter Property="TabNavigation" Value="Once" />
<Setter Property="ScrollViewer.HorizontalScrollBarVisibility" Value="Auto"/>
<Setter Property="ScrollViewer.VerticalScrollBarVisibility" Value="Auto"/>
<Setter Property="BorderBrush"> ...
好,之後在同一個定義你的ItemTemplate XAML:
<DataTemplate x:Key="MyItemTemplate">
,並把它添加到你的列表框樣式的二傳手名單:
<Style TargetType="local:MyListBox">
<Setter Property="ItemTemplate" Value="{StaticResource MyItemTemplate}"/>^
現在這是您的默認模板。
但是你需要添加任何特定的行爲到你的ListBox,因爲你想從它繼承。如果你只是想添加特定的項目模板,我不會推薦從ListBox派生(事實上,DataTemplate不是通用的,它總是特定於DataType)。如果你不添加特定的行爲,我會去創建一個全局的DataTemplate(可能定義在你的app.xaml中),並在每次需要時將它作爲DataTemplate引用,否則我會用這個DataTemplate創建一個特定的樣式,並將樣式設置爲常見的ListBox。
如果您有任何問題,請發表評論。
希望這會有所幫助!
BR,
TJ