Search code examples
c#xamluwpwinui-3winui

x:Bind in WinUI3 Binding to a datetime


I am trying to bind current DateTime to a textblock object in WinUI3.

<Page
    x:Class="HabitTracker.Screens.HomePage"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="using:HabitTracker.Screens"
    xmlns:sys="using:System"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d"
    Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
    <Grid> 
      <Grid>
        <GridView MaxHeight="500" ItemsSource="{x:Bind Habits}">
          <GridView.HeaderTemplate>
           <DataTemplate>
            <StackPanel Orientation="Horizontal" Spacing="45">
             <TextBlock Text="{x:Bind sys:DateTime.Now}" />
             <TextBlock Text="hello2" />
             <TextBlock Text="hello2" />
             <TextBlock Text="hello2" />
            <TextBlock Text="hello2" />
         </StackPanel>
       </DataTemplate>
    </GridView.HeaderTemplate>

... But my binding doesn't work. I get empty string on the UI while running the application.

I have the following namespace declaration:

xmlns:sys="using:System"

What am I missing?

Note: I also read this doc https://learn.microsoft.com/en-us/windows/uwp/data-binding/function-bindings although it is for UWP, not WinUi3 documentation.

I am using WindowsAppSDK 1.1.1


Solution

  • I could reproduce your behavior when putting the Textblock into a DataTemplate of a ListView.HeaderTemplate. I'm not sure about the reason but I suspect the behavior is related to the DataContext. When you put the TextBlock into a DataTemplate, the DataContext will be changed into the root control of the GridView template.

    A workaround that I used is to put the TextBlock into a UserControl instead of directly putting the TextBlockinto the DataTemplate.

    UserControl:

     <StackPanel>
        <TextBlock Text="{x:Bind sys:DateTime.Now}" />
    </StackPanel>
    

    Page:

     <ListView x:Name="MyListView" Width="500" Height="500" >
            <ListView.HeaderTemplate>
                <DataTemplate >
                    <StackPanel>
                        <local:UserControl1 />
                        <TextBlock Text="Hello"/>
                        <TextBlock Text="Hello"/>
                        <TextBlock Text="Hello"/>
                        <TextBlock Text="Hello"/>
                    </StackPanel>
                </DataTemplate>
            </ListView.HeaderTemplate>
            <x:String >123</x:String>
            <x:String >123</x:String>
            <x:String >123</x:String>
            <x:String >123</x:String>
        </ListView>
    

    What it looks like:

    enter image description here