I find that there is some item templates, data templates and binding in the .xaml file for listbox. Is there any way to create it in code behind?
Is there any way to create data templates programataically?
this is the XAML CODE,BUT I need in code behind using c# not in XAML,because am working in dynamic list box creation with adding itemtemplatem,datatemplate
<ListBox Height="520" HorizontalAlignment="Left" Margin="0,6,0,0" Name="lstimge" VerticalAlignment="Top" Width="450" >
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal"&g开发者_开发百科t;
<Image Source="{Binding Image}" Width="150" Stretch="Uniform" HorizontalAlignment="Center" />
<TextBlock Text="{Binding FileName}" TextWrapping="Wrap" />
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
Kindly give the solution
Thanks, Ashok
You can't build templates from code - this can only be done from XAML.
If you dynamically generated the template XAML in your code, you could load it as described here.
I suspect you'll find yourself opening a whole can of worms if you go down this route. As an alternative, you could predefine a set of templates, and choose the correct one dynamically at runtime, as described here
You could use XamlReader.Load to dynamically load XAML in code-behind and cast it to a DataTemplate, later assigning it to the ItemTemplate. Here is an example.
Is the DataTemplate that you want to use the same for all listboxes or is that also dynamically generated? If it is the same for all of them then you could save it as a Style in your Resources and then just create the Listbox object dynamically and apply the style.
精彩评论