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

时间:2013-01-18 17:03:45

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

我有一个ItemsJSectionLongListMultiSelector个对象,我会传递给JSection。我想直接将每个controls:Section传递给每个<toolkit:LongListMultiSelector ItemsSource="{Binding Items}"> <toolkit:LongListMultiSelector.ItemTemplate> <DataTemplate> <controls:Section Data="{Binding}" /> </DataTemplate> </toolkit:LongListMultiSelector.ItemTemplate> </toolkit:LongListMultiSelector> 。我怎么能这样做?

导致运行时异常的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(); } } } 的XAML的UserControl:

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

我得到的例外:

{{1}}

2 个答案:

答案 0 :(得分:0)

经过一些搜索,我发现我根本不需要设置任何明确的绑定,每JSectionDataContext都是Section

此代码正常运行并且没有例外:

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

答案 1 :(得分:0)

您可以将任何集合绑定为LongList Selector.ItemSsource = Collection 任何ListElement [i]的Datacontext都将自动设置为相应的Collection [i]元素。