我尝试使用DataTemplate显示单个项(不包含在集合中)。这是我到目前为止得到的,没有显示任何内容。替代
ItemsControl
具有
ListBox
显示一个空列表框(因此我知道元素在那里)。
<ItemsControl
ItemsSource="{Binding Session}"
ItemTemplate="{StaticResource SessionHeaderDataTemplate}"
/>
Session
是单个对象。我想使用一个数据模板,因为我在应用程序的其他地方显示相同的信息,并且希望将表示样式定义为一个资源,这样我就可以在一个地方更新它。
有什么想法,或者我应该在我的视图模型中创建一个单元素集合并绑定到它吗?
编辑:这就是我最终要做的,尽管下面的答案也是一个解决方案。我对我的
DataTemplates
所以把这样的东西推到另一个XAML文件中不太舒服。
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");
}
}
}