create datatemplate code behind

前端 未结 3 563
一向
一向 2021-01-14 05:57

I am trying to create a ListBox view for show data, and I want it to contain a ListBox with a datatemplate for 2 columns \"Product ID & Product Barcode\"

I want

3条回答
  •  天命终不由人
    2021-01-14 06:52

    Conditional XAML DataTemplate

    Defining a static DataTemplate in your object's XAML file is the customary way to approach this. Also, the example Microsoft provides for DataTemplate.LoadContent() is nifty for showing how to switch templates dynamically at run-time (see DataTemplate.LoadContent method) when needed.

    However, if you have a special requirement of conditional XAML compilation (like omitting debug-only XAML when you're building a Release version), you will need to resort to the XamlReader.Load() approach (see XamlReader.Load method).

    To that end, I thought a bit more detailed example might be helpful. Here, I have a debug-only ListView that is bound to an ObservableCollection<> of custom objects. The ListView is not defined in static XAML, since it's needed only in Debug mode ...


    Custom class:

        class ActiveNotification
        {
            public String Name { get; set; }
            public String Type { get; set; }
            public String DayOfWeek { get; set; }
            public DateTime DeliveryTime { get; set; }
            public String Id { get; set; }
        }
    

    Private member variables:

        readonly ObservableCollection _activeNotifications = new ObservableCollection();
        readonly ListView listViewNotifications = 
            new ListView 
            { 
                Visibility = Visibility.Collapsed,
                HorizontalAlignment = HorizontalAlignment.Left,
                VerticalAlignment = VerticalAlignment.Bottom,
            };
    

    Load-time ListView setup:

            // Set up notifications list
            listViewNotifications.SetBinding(ListView.ItemsSourceProperty, new Binding { Source = _activeNotifications });
            listViewNotifications.Tapped += listViewNotifications_Tapped;
            Grid.SetRowSpan(listViewNotifications, 2);
            Grid.SetColumnSpan(listViewNotifications, 2);
            var xamlString =
                "" +
                    "" +
                        "" +
                        "" +
                        "" +
                        "" +
                        "" +
                    "" +
                "";
            var dataTemplate = (DataTemplate)XamlReader.Load(xamlString);
            listViewNotifications.ItemTemplate = dataTemplate;
            GridMain.Children.Add(listViewNotifications);
    

提交回复
热议问题