【问题标题】:Pass binded object directly into DataTemplate item将绑定对象直接传递到 DataTemplate 项
【发布时间】:2013-01-18 17:03:44
【问题描述】:

我有一个集合 ItemsJSection 对象,我传递给 LongListMultiSelector。我想直接将每个JSection 传递给每个controls:Section。我该怎么做?

导致运行时异常的 XAML:

<toolkit:LongListMultiSelector ItemsSource="{Binding Items}">
    <toolkit:LongListMultiSelector.ItemTemplate>
        <DataTemplate>
            <controls:Section Data="{Binding}" />
        </DataTemplate>
    </toolkit:LongListMultiSelector.ItemTemplate>
</toolkit:LongListMultiSelector>

包含带有 LongListMultiSelector 的 XAML 的用户控件:

namespace Controls
{
    public partial class RemoteHomePage : UserControl
    {
        public ObservableCollection<JSection> Items { get; set; }

        public RemoteHomePage()
        {
            Items = new ObservableCollection<JSection> { };

            Items.Add(new JSection { id = 2, name = "Section 2" });
            Items.Add(new JSection { id = 1, name = "Section 1" });
            Items.Add(new JSection { id = 3, name = "Section 3" });

            InitializeComponent();
        }
    }
}

Section类:

namespace Controls
{
    public partial class Section : UserControl
    {
        public JSection Data { get; set; }

        public Section()
        {
            InitializeComponent();
        }
    }
}  

我得到的例外:

An exception of type 'System.ArgumentException' occurred in mscorlib.ni.dll and wasn't handled before a managed/native boundary
An exception of type 'System.IO.FileNotFoundException' occurred in Unknown Module. and wasn't handled before a managed/native boundary
An exception of type 'MS.Internal.NativeParseException' occurred in Unknown Module. and wasn't handled before a managed/native boundary
An exception of type 'System.Exception' occurred in Unknown Module. and wasn't handled before a managed/native boundary

【问题讨论】:

  • 有什么例外? Items 属性的定义和设置在哪里?
  • @JustinAngel 我已经更新了我的问题。

标签: c# xaml data-binding windows-phone-8


【解决方案1】:

经过一番搜索,我发现我根本不需要设置任何显式绑定,每个JSection 都将是每个DataContextDataContext

这段代码运行良好,没有异常:

<toolkit:LongListMultiSelector ItemsSource="{Binding Items}">
    <toolkit:LongListMultiSelector.ItemTemplate>
        <DataTemplate>
            <controls:Section />
        </DataTemplate>
    </toolkit:LongListMultiSelector.ItemTemplate>
</toolkit:LongListMultiSelector>

【讨论】:

    【解决方案2】:

    您可以将任何集合绑定为 LongListSelector.ItemSource=Collection 任何 ListElement[i] 的数据上下文都会自动设置为对应的 Collection[i] 元素。

    【讨论】:

      猜你喜欢
      • 2016-03-17
      • 1970-01-01
      • 1970-01-01
      • 2011-12-01
      • 1970-01-01
      • 1970-01-01
      • 2015-08-06
      • 2014-08-26
      • 2018-09-30
      相关资源
      最近更新 更多