how to create dataTemplate in code cs file?

mc 5,426 Reputation points
2023-08-04T00:28:47.59+00:00

how to create dataTemplate in listView?

not in xaml?

Windows development Windows App SDK
{count} votes

2 answers

Sort by: Most helpful
  1. Castorix31 90,521 Reputation points
    2023-08-11T14:33:02.02+00:00

    You can use XamlReader.Load

    A test with a ListView with 2 columns :

                string sXAML =
                     "<DataTemplate xmlns=\"http://schemas.microsoft.com/winfx/2006/xaml/presentation\">" +
                    " <Grid Height=\"48\" >" +
                    "      <Grid.ColumnDefinitions>" +
                    "                 <ColumnDefinition Width=\"150\"/>" +
                    "                 <ColumnDefinition Width=\"100\"/>" +
                    "      </Grid.ColumnDefinitions>" +
                    "      <TextBlock Grid.Column=\"0\" VerticalAlignment=\"Center\" Style=\"{ThemeResource BaseTextBlockStyle}\" Text=\"{Binding Name}\" />" +
                    "      <TextBlock Grid.Column=\"1\" VerticalAlignment=\"Center\" HorizontalAlignment=\"Left\" Text=\"{Binding Type}\"/>" +
                    " </Grid>" +
                    "</DataTemplate>";
                var ItemTemplate = (DataTemplate)XamlReader.Load(sXAML);
                lv1.ItemTemplate = ItemTemplate;
                lv1.ItemsSource = files; 
    

    with :

     ObservableCollection<File> files = new ObservableCollection<File>();
    
     files.Add(new File("File1", "Type1"));
     files.Add(new File("File2", "Type2"));
    
        public class File
        {
            #region Properties
            public string Name { get; set; }
            public string Type { get; set; }
            #endregion
            public File(string sName, string sType)
            {
                Name = sName;
                Type = sType;           
            }
        }
    

    User's image

    1 person found this answer helpful.
    0 comments No comments

  2. Xiaopo Yang - MSFT 12,731 Reputation points Microsoft External Staff
    2023-08-04T02:09:11.2166667+00:00

    Hello @mc,

    There is a WPF example: https://stackoverflow.com/a/248638/15511041. Not Test in WinUI3.


Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.