kw1jybo
kw1jybo

Reputation: 152

How to setup a template for a ListBox with a DataTemplate

So I have the following ListBox defined:

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

There are going to be a number of these, where the only things that changes is the placement (Grid location) and the ItemsSource bindings. Everything else is going to be the same. Question is how do I setup a template so all the ListBoxes use it.

Upvotes: 2

Views: 48

Answers (1)

kmatyaszek
kmatyaszek

Reputation: 19296

You can define style in application resources and applied it to ListBox later in your code.

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

Using of this style:

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

Upvotes: 1

Related Questions