将绑定对象直接传递到DataTemplate项

本文关键字:DataTemplate 绑定 对象 | 更新日期: 2023-09-27 17:54:29

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

导致运行时异常的XAML:
<toolkit:LongListMultiSelector ItemsSource="{Binding Items}">
    <toolkit:LongListMultiSelector.ItemTemplate>
        <DataTemplate>
            <controls:Section Data="{Binding}" />
        </DataTemplate>
    </toolkit:LongListMultiSelector.ItemTemplate>
</toolkit:LongListMultiSelector>

UserControl,包含XAML与LongListMultiSelector:

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 class:

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

将绑定对象直接传递到DataTemplate项

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

下面的代码运行良好,不会产生异常:

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

您可以将任何集合绑定为LongListSelector。ItemSource =集合任意ListElement[i]的Datacontext将自动设置为对应的Collection[i]元素