代码之家  ›  专栏  ›  技术社区  ›  geofftnz

如何在Silverlight中使用数据模板显示单个项目?

  •  14
  • geofftnz  · 技术社区  · 17 年前

    我尝试使用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");
                }
            }
        }
    
    2 回复  |  直到 17 年前
        1
  •  30
  •   Wallstreet Programmer    17 年前

    对于没有代码隐藏的简单视图,坚持使用数据模板,而不必创建其他用户控件。使用ContentControl显示单个项的数据模板。

     <ContentControl 
          ContentTemplate="{StaticResource SessionHeaderDataTemplate}" 
          Content="{Binding Path=Session}" />
    
        2
  •  1
  •   mattmanser    17 年前

    您不需要使用itemsControl来实现这一点,只需创建一个自定义用户控件,然后绑定到该控件,例如。

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

    自定义控件可以有自己的XAML文件,因此它可以按您的需要查看。

    推荐文章