views:

458

answers:

2

I am trying to display a single item (not contained in a collection) using a DataTemplate. Here's what I've got so far, which is displaying nothing. Replacing ItemsControl with ListBox displays an empty listbox (so I know the element is there).

        <ItemsControl
            ItemsSource="{Binding Session}"
            ItemTemplate="{StaticResource SessionHeaderDataTemplate}"
            />

Session is a single object. I want to use a DataTemplate because I am displaying the same information elsewhere in my app and wanted the presentation style defined as a resource so I can update it in one place.

Any ideas, or should I create a 1-element collection in my ViewModel and bind to that?

Edit: This is what I ended up doing, although the answer below is also a solution. I'm quite attached to my DataTemplates so didnt feel comfortable having something like this pushed out to another XAML file.

XAML:

        <ItemsControl
            DataContext="{Binding}"
            ItemsSource="{Binding Session_ListSource}"
            ItemTemplate="{StaticResource SessionHeaderDataTemplate}" />

ViewModel:

    private Session m_Session;
    public Session Session
    {
        get { return m_Session; }
        set
        {
            if (m_Session != value)
            {
                m_Session = value;
                OnPropertyChanged("Session");

                // Added these two lines 
                Session_ListSource.Clear();
                Session_ListSource.Add(this.Session);
            }
        }
    }

    // Added this property.
    private ObservableCollection<Session> m_Session_ListSource = new ObservableCollection<Session>();
    public ObservableCollection<Session> Session_ListSource
    {
        get { return m_Session_ListSource; }
        set
        {
            if (m_Session_ListSource != value)
            {
                m_Session_ListSource = value;
                OnPropertyChanged("Session_ListSource");
            }
        }
    }
A: 

You don't need to use an ItemsControl to do that, just create a custom user control, then bind to that, e.g.

<TestProject:myControl DataContext="{Binding Session}" />

The custom control can have it's own xaml file so it can look however you want it to.

mattmanser
I'm going to mark this as the answer because it's a workable solution, but I ended up making a 1-element collection to bind to because I prefer keeping all my reusable data templates in one place.
geofftnz
+3  A: 

Stick with your datatemplates for simple views with no code behind instead of having to create another user controls. Use a ContentControl to display your DataTemplate for a single item.

 <ContentControl 
      ContentTemplate="{StaticResource SessionHeaderDataTemplate}" 
      Content="{Binding Path=Session}" />
Wallstreet Programmer
Exactly what I was after!
geofftnz
Didn't think of that, nice
mattmanser