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");
}
}
}