Добавление шаблона данных в список и программу формы элементов панорамы в Windows Phone 7

Я динамически добавляю элементы панорамы в элементы управления панорамой, они успешно добавляются без каких-либо проблем.

но когда я пытаюсь добавить список в элемент панорамы, это дает ошибку. Я также не могу увидеть исключение, приложение автоматически закрывается, и после этого я вижу домашний экран эмулятора.

Ниже приведен мой код, который я написал для создания элемента панорамы и списка.

lstAnniversaries = new ListBox()
lstAnniversaries.Width = 420;
                        lstAnniversaries.HorizontalAlignment = System.Windows.HorizontalAlignment.Left;
                        lstAnniversaries.Foreground = new SolidColorBrush(FacebookQueries.GetColorFromHexString("#000000"));
                        lstAnniversaries.Background = new SolidColorBrush(FacebookQueries.GetColorFromHexString("#ffffff"));
                        lstAnniversaries.Tap += new EventHandler<System.Windows.Input.GestureEventArgs>(lstUpcoming_Tap);
                        lstAnniversaries.ItemTemplate = (DataTemplate)XamlReader.Load(@"<DataTemplate xmlns=""http://schemas.microsoft.com/winfx/2006/xaml/presentation"" xmlns:x=""http://schemas.microsoft.com/winfx/2006/xaml"">
<Grid  Height=""100"" Margin=""0,0,0,0"">
            <Grid.ColumnDefinitions>
                <ColumnDefinition Width=""90"" />
                <ColumnDefinition Width=""210"" />
                <ColumnDefinition Width=""*"" />
            </Grid.ColumnDefinitions>
            <Image Source=""{Binding ImageSource}"" Height=""90"" Width=""90"" Margin=""0,0,11,0"" />
            <StackPanel Grid.Column=""1"" Margin=""0,10,0,0"">
                <TextBlock Text=""{Binding NameSource}"" Style=""{StaticResource ProfileNameStyleForTextBlock}""  />
                <StackPanel Orientation=""Horizontal"" Margin=""0,-2,0,0"">
                    <TextBlock Text=""{Binding EventName}"" Foreground=""#000000"" Style=""{StaticResource EventNameStyleForTextBlock}""   />
                    <TextBlock Text=""{Binding EventDate}"" Foreground=""{Binding EventColor}"" Style=""{StaticResource EventDateStyleForTextBlock}""  />
                </StackPanel>
            </StackPanel>
            <Button VerticalAlignment=""Center"" Height=""Auto""     Name=""btnAnniversary"" Width=""75"" Margin=""5,0,0,0"" HorizontalAlignment=""Left""     Visibility=""{Binding EllipseStatus}"" Tag=""{Binding BindsDirectlyToSource=True}""     Click=""btnAnniversary_Click"" Canvas.ZIndex=""1"" Grid.Column=""2"">
                <Image  Source=""/GiftGiv;component/Assets/bubble.png"" />
            </Button>
        </Grid>
    </DataTemplate>");
                        pan_anniversaries = new PanoramaItem();
                        pan_anniversaries.HeaderTemplate =     (DataTemplate)XamlReader.Load(@"<DataTemplate     xmlns=""http://schemas.microsoft.com/winfx/2006/xaml/presentation""     xmlns:x=""http://schemas.microsoft.com/winfx/2006/xaml""><TextBlock Text=""anniversaries""    FontSize=""54"" Foreground=""Black"" Margin=""-10,0,0,0""></TextBlock></DataTemplate>");

                        Grid grd = new Grid();
                        grd.Children.Add(lstAnniversaries);

                        pan_anniversaries.Content = grd;

                        PanoramaControl.Items.Add(pan_anniversaries);

РЕДАКТИРОВАТЬ:

Текст окна вывода

A first chance exception of type 'System.InvalidOperationException' occurred in System.Core.dll
A first chance exception of type 'System.InvalidOperationException' occurred in System.Core.dll
Step into: Stepping over method without symbols 'System.Reflection.RuntimeMethodInfo.InternalInvoke'
Step into: Stepping over method without symbols 'System.Reflection.MethodBase.Invoke'
Step into: Stepping over method without symbols 'System.Delegate.DynamicInvokeOne'
Step into: Stepping over method without symbols     'System.MulticastDelegate.DynamicInvokeImpl'
Step into: Stepping over method without symbols 'System.Delegate.DynamicInvoke'
Step into: Stepping over method without symbols     'System.Windows.Threading.DispatcherOperation.Invoke'
Step into: Stepping over method without symbols 'System.Windows.Threading.Dispatcher.Dispatch'
Step into: Stepping over method without symbols 'System.Windows.Threading.Dispatcher.OnInvoke'
Step into: Stepping over method without symbols 'System.Windows.Hosting.CallbackCookie.Invoke'
Step into: Stepping over method without symbols 'System.Windows.Hosting.DelegateWrapper.InternalInvoke'
Step into: Stepping over method without symbols 'System.Windows.RuntimeHost.ManagedHost.InvokeDelegate'
A first chance exception of type 'System.Exception' occurred in System.Windows.dll
A first chance exception of type 'MS.Internal.WrappedException' occurred in     System.Windows.dll
A first chance exception of type 'MS.Internal.WrappedException' occurred in System.Windows.dll
A first chance exception of type 'MS.Internal.WrappedException' occurred in System.Windows.dll
A first chance exception of type 'MS.Internal.WrappedException' occurred in System.Windows.dll
A first chance exception of type 'MS.Internal.WrappedException' occurred in System.Windows.dll
A first chance exception of type 'System.Exception' occurred in System.Windows.dll
A first chance exception of type 'MS.Internal.WrappedException' occurred in System.Windows.dll
A first chance exception of type 'MS.Internal.WrappedException' occurred in System.Windows.dll
A first chance exception of type 'MS.Internal.WrappedException' occurred in System.Windows.dll
A first chance exception of type 'MS.Internal.WrappedException' occurred in System.Windows.dll
A first chance exception of type 'MS.Internal.WrappedException' occurred in System.Windows.dll
The thread '<No Name>' (0xf640c32) has exited with code 0 (0x0).
The thread '<No Name>' (0xf450ca6) has exited with code 0 (0x0).
The thread '<No Name>' (0xf050d2e) has exited with code 0 (0x0).
The thread '<No Name>' (0xf820cda) has exited with code 0 (0x0).
The thread '<No Name>' (0xecb0e52) has exited with code 0 (0x0).

person Raghuveer    schedule 03.08.2012    source источник
comment
Зачем это делать в коде? Почему бы вам не добавить этот DataTemplate к ресурсам страницы или приложения под каким-либо ключом, а затем получить его по этому ключу? Можете ли вы увидеть, какое исключение возникает и где (проверьте окно вывода при отладке)   -  person Igor Ralic    schedule 03.08.2012
comment
@igrali Why don't you add that DataTemplate to Page or App resources under some key and then retrieve it by that key? Ты знаешь, как это сделать??   -  person Raghuveer    schedule 03.08.2012
comment
Я обновил свой вопрос с текстом окна вывода, проверьте его еще раз   -  person Raghuveer    schedule 03.08.2012
comment
Да, просто добавьте его, как показано на картинке в этом сообщении блога: mobileappchallenge.wordpress.com/2011/09/07/ Тогда на вашей странице появится этот ресурс. После этого просто сделайте что-то вроде этого: lstAnniversaries.DataTemplate = this.Resources[MyResourceKey] as DataTemplate; где MyResourceKey — это ключ, который вы установили в своем шаблоне данных. Это упростит ваш код!   -  person Igor Ralic    schedule 03.08.2012
comment
@igrali О, спасибо, я попробую и дам тебе знать...   -  person Raghuveer    schedule 03.08.2012
comment
@igrali Да, это работает Создание DataTemplate из кода, я думаю, создает проблему. Спасибо.   -  person Raghuveer    schedule 03.08.2012


Ответы (1)


Вместо того, чтобы создавать DataTemplates в файле кода, добавьте код DataTemplate в раздел ресурсов Страницы или ПРИЛОЖЕНИЯ.

Используйте следующий способ, чтобы решить проблему, как упоминал @igrali в комментариях.

 lstAnniversaries.ItemTemplate = this.Resources["AnniversariesTemplate"] as DataTemplate;
 lstAnniversaries.Style = this.Resources["EventsListStyle"] as Style; 
person Raghuveer    schedule 21.08.2012