microsoft / xaml-standard

XAML Standard : a set of principles that drive XAML dialect alignment
Other
804 stars 50 forks source link

Simpler data template syntax #236

Open VBAndCs opened 5 years ago

VBAndCs commented 5 years ago

I am developing Vazor, a VB.NET Razor built on xml literals supported in VB.NET code. I cam up with an idea to use simple data templates like this:

     <ul>
         <li ForEach="m">
             <p>Id: <m.Id/></p>
             <p>Name: <m.Name/></p>
             <p>Grade: <m.Grade/></p>
         </li>
     </ul>

Note: you can use any var name other than m.

I manage to do it by using Reflection in the function ParseTemplate: https://github.com/VBAndCs/Vazor/blob/master/Vazor/VazorExtensions.vb

I think XAML can make use of this simple template formula, instead of XAML DataTemplate which is rather complex and verbose.

<ListBox x:Name="Lst1">
  <StackPanel >
     <ItemsControl ForEach="m" Type="Student">
        <TextBlock>Id: <m.Id/></TextBlock>
        < TextBlock>Name: <m.Name/></TextBlock>
        < TextBlock>Grade: <m.Grade/></TextBlock>
     </ItemsControl>
  </StackPanel >
</ListBox>

The ListBox.ItemsSource will be the data source used by the template to generate the items.

Another idea, based on Razor and xml literals: Allow us to write VB and C# in Xaml!

<ListBox x:Name="Lst1">
  <StackPanel >
    <%= For Each m in ItemsSource 
     Yield _
      <ItemsControl>
        <TextBlock>Id: <%= m.Id %></TextBlock>
        < TextBlock>Name: <%= m.Name %></TextBlock>
        < TextBlock>Grade: <%= m.Grade %></TextBlock>
     </ItemsControl>
   Next %>
  </StackPanel >
</ListBox>

In fact, the above code can be written in VB today like this:

Dim Xaml = 
<ListBox Name="Lst1">
  <StackPanel >
    <%= (Iterator Function()
    For Each m in Lst1.ItemsSource
      Yield _
      <ItemsControl>
        <TextBlock>Id: <%= m.Id %></TextBlock>
        < TextBlock>Name: <%= m.Name %></TextBlock>
        < TextBlock>Grade: <%= m.Grade %></TextBlock>
     </ItemsControl>
   Next 
End Function)( )%>
  </StackPanel >
</ListBox>

And it generates something like this:

<ListBox Name="Lst1">
  <StackPanel>
    <ItemsControl>
      <TextBlock>Id: 1</TextBlock>
      <TextBlock>Name: Adam</TextBlock>
      <TextBlock>Grade: 87</TextBlock>
    </ItemsControl>
    <ItemsControl>
      <TextBlock>Id: 2</TextBlock>
      <TextBlock>Name: Tom</TextBlock>
      <TextBlock>Grade: 30</TextBlock>
    </ItemsControl>
    <ItemsControl>
      <TextBlock>Id: 3</TextBlock>
      <TextBlock>Name: Sara</TextBlock>
      <TextBlock>Grade: 60</TextBlock>
    </ItemsControl>
  </StackPanel>
</ListBox>