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

时间:2009-02-18 23:04:11

标签: silverlight data-binding datatemplate

我正在尝试使用DataTemplate显示单个项目(未包含在集合中)。这是我到目前为止所得到的,没有显示任何内容。用ItemsControl替换ListBox会显示一个空的列表框(所以我知道元素在那里)。

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

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

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

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

XAML:

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

视图模型:

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

2 个答案:

答案 0 :(得分:30)

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

 <ContentControl 
      ContentTemplate="{StaticResource SessionHeaderDataTemplate}" 
      Content="{Binding Path=Session}" />

答案 1 :(得分:1)

您不需要使用ItemsControl来执行此操作,只需创建自定义用户控件,然后绑定到该控件,例如

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

自定义控件可以拥有自己的xaml文件,因此它可以看起来像你想要的那样。