How to Draw items by code in a  WPF ListBox?

bish wakim
bish wakim used Ask the Experts™
on
After I have populated the items of my ListBox with  objects that contain several fields  I have got some composed stings written inside the items.
Althoug I wish that these items continue to hold the objects in memory , I want only  one field of my object to appear visually. How can I do it in WPF C#?
Thanks
Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
You can create DataTemplate for ListBoxItem and assign it to your ListBox like:

Place it in your resources
<DataTemplate x:Name="ListBoxItemEx">
              <StackPanel Orientation="Vertical" Width="280" Height="200">
                <TextBlock Text="{Binding title}" FontWeight="Bold" />
                <TextBlock Text="{Binding content}" TextWrapping="Wrap" />
              </StackPanel>
</DataTemplate>

Then in your ListBox attach it to property ItemTemplate like:

<ListBox x:Name="Scroller" Width="300" Height="200" ItemTemplate={StaticResources ListBoxItemEx} />

Inside your DataTemplate you can set any appereance for your item, but ListBoxItem will still have your full object data.

If you want to set template from code behind just well form you DataTemplate as string and use this code snippet to attach new template:

Scroller.ItemTemplate = (DataTemplate)XamlReader.Load(reader.Value);

Author

Commented:
I need  to try it.  I'll come back to you  tomorrow.  
Thanks

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial