如何在Silverlight中使用DataTemplate显示单个项目?

geo*_*tnz 14 data-binding silverlight datatemplate

我试图使用DataTemplate显示单个项目(不包含在集合中).这是我到目前为止所得到的,没有显示任何内容.更换ItemsControlListBox显示一个空列表框(所以我知道该元素是存在的).

        <ItemsControl
            ItemsSource="{Binding Session}"
            ItemTemplate="{StaticResource SessionHeaderDataTemplate}"
            />
Run Code Online (Sandbox Code Playgroud)

Session是一个单一的对象.我想使用DataTemplate,因为我在我的应用程序的其他地方显示相同的信息,并希望将演示文稿样式定义为资源,以便我可以在一个地方更新它.

任何想法,或者我应该在我的ViewModel中创建一个1元素集合并绑定到那个?

编辑:这是我最终做的,虽然下面的答案也是一个解决方案.我非常依赖我,DataTemplates所以不觉得把这样的东西推到另一个XAML文件中.

XAML:

        <ItemsControl
            DataContext="{Binding}"
            ItemsSource="{Binding Session_ListSource}"
            ItemTemplate="{StaticResource SessionHeaderDataTemplate}" />
Run Code Online (Sandbox Code Playgroud)

视图模型:

    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");
            }
        }
    }
Run Code Online (Sandbox Code Playgroud)

Wal*_*mer 31

坚持使用您的数据模板以获得简单的视图,而无需代码,而不必创建另一个用户控件.使用ContentControl为单个项目显示DataTemplate.

 <ContentControl 
      ContentTemplate="{StaticResource SessionHeaderDataTemplate}" 
      Content="{Binding Path=Session}" />
Run Code Online (Sandbox Code Playgroud)

  • 正是我所追求的! (2认同)