I'm trying to load a template for displaying a list box.Here i have two different templates
and i have to load one template depending upon the configuration value.First give some idea
that how to load different templates for a single list box.
Here is my XAML code
<Window x:Class="DynamicTemplate.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:local="clr-namespace:DynamicTemplate"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Window1" Height="300" Width="300">
<Window.Resources>
<ResourceDictionary>
<DataTemplate x:Key="LargeTemplate">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition/>
</Grid.ColumnDefinitions>
<TextBlock Text="Large Template" FontSize="10" Foreground="Black"/>
</Grid>
</DataTemplate>
<DataTem开发者_StackOverflow中文版plate x:Key="SmallTemplate">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition/>
</Grid.ColumnDefinitions>
<TextBlock Text="Small template" FontSize="10" Foreground="Blue"/>
</Grid>
</DataTemplate>
</ResourceDictionary>
</Window.Resources>
<ListBox x:Name="MyListBox" Width="200" Height="200" ItemsSource="{Binding Path=list1}" >
<ListBox.Style>
<Style TargetType="ListBox">
<Style.Triggers>
<DataTrigger Binding="{Binding Path=size}" Value="Small">
<Setter Property="ListBox.ItemTemplate" Value="{StaticResource SmallTemplate}"/>
</DataTrigger>
<DataTrigger Binding="{Binding Path=size}" Value="Large">
<Setter Property="ListBox.ItemTemplate" Value="{StaticResource LargeTemplate}"/>
</DataTrigger>
</Style.Triggers>
</Style>
</ListBox.Style>
</ListBox>
</Window>
Please try to help me i need to do this now. please check the code and reply me soon. Thanks in advance.
Instead of style triggers in xaml i have used FindResource method like this in my .cs file
Here is my code
string alertTemplateStyle = ConfigurationManager.AppSettings["AlertTemplateStyle"];
//it will return the value of my configuration file either 1 or 2 depending
// upon user requirement
DataTemplate template = null;
int size = int.Parse(alertTemplateStyle);
if (size == 1)
{
template = this.FindResource("SmallTemplate") as DataTemplate;
}
else
{
template = this.FindResource("LargeTemplate") as DataTemplate;
}
AlertsListBox.ItemTemplate = template;//AlertsListBox is my xaml listbox name
What is wrong with your current suggestion?
I guess you could use a DataTemplateSelector to achieve something similar, even though I think DataTemplateSelector usually switches the used DataTemplate based on the items themselves.
//daniel
精彩评论