如何使用DataTemplate

时间:2018-08-25 14:58:28

标签: wpf

所以我定义了以下列表框:

<ListBox Grid.Row="1" Grid.Column="0" x:Name="RawLBControl" 
     ItemsSource="{Binding ProductionLists.Raw}" 
     Background="LightGray" BorderThickness="2" BorderBrush="Black">
<ListBox.ItemTemplate>
    <DataTemplate>
        <TextBox Text="{Binding Mode=OneWay}" Background="LightGray"/>
    </DataTemplate>
</ListBox.ItemTemplate>
</ListBox>

会有许多这样的地方,唯一改变的是放置(网格位置)和ItemsSource绑定。其他一切都将是相同的。问题是如何设置模板,以便所有列表框都使用它。

1 个答案:

答案 0 :(得分:1)

您可以在应用程序资源中定义样式,然后在代码中将其应用于ListBox

<Application x:Class="Q52018469.App"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             StartupUri="MainWindow.xaml">
    <Application.Resources>
        <Style x:Key="MyListBoxStyle" TargetType="ListBox">
            <Setter Property="Background" Value="LightGray"/>
            <Setter Property="BorderThickness" Value="2"/>
            <Setter Property="BorderBrush" Value="Black"/>
            <Setter Property="ItemTemplate">
                <Setter.Value>
                    <DataTemplate>
                        <TextBox Text="{Binding Mode=OneWay}" Background="LightGray"/>
                    </DataTemplate>
                </Setter.Value>
            </Setter>
        </Style>
    </Application.Resources>
</Application>

使用这种样式:

...
<Grid>
   ...
   <ListBox Grid.Row="1" Grid.Column="0" x:Name="RawLBControl" 
            ItemsSource="{Binding ProductionLists.Raw}" 
            Style="{StaticResource MyListBoxStyle}" />
</Grid>
...