Search code examples
c#bindinguser-controlswinui-3winui

Can a user control perform binding when part of a ListView in WinUI?


I'm trying to use a UserControl-derived control (UpdateBlockControl) inside the DataTemplate of a ListView, like this:

    <ListView x:Name="AppsListView">
       <ListView.ItemTemplate>
          <DataTemplate x:DataType="model:AppBase">
             <StackPanel Orientation="Horizontal">
                <local:UpdateBlockControl ImageSource="{x:Bind ImageSource}" AppName="{x:Bind Name}"/>
                <TextBlock Text="{x:Bind Name}" Foreground="Orange" Margin="8,0,0,0" />
                <TextBlock Text="{x:Bind ImageSource}" Margin="8,0,0,0" Foreground="LimeGreen"/>
             </StackPanel>
          </DataTemplate>
       </ListView.ItemTemplate>
    </ListView>

UpdateBlockControl is derived from UserControl and I'm trying to bind its properties (ImageSource and AppName) to the model's (AppBase) properties.

You can see me trying to set up these bindings in the first item in the StackPanel. Just to see if the binding works at all, I also bind a couple of TextBlocks to these properties.

The XAML for UserBlockControl is essentially this:

    <StackPanel Orientation="Vertical">
        <TextBlock Text=":-)"/>
        <TextBlock Text="{x:Bind AppName}"/>
        <TextBlock Text="{x:Bind ImageSource}"/>
    </StackPanel>

When I run the application I see the following:

enter image description here

So the UserControl properties aren't working correctly it would seem: I get the :-) for the first TextBlock but the second and third TextBlocks are empty. Their equivalents in the ListView do work however (see image, above).

Should I be able to use a user control insisde a DataTemplate like this? If so, why aren't the bindings working?


Solution

  • x:Bind is Mode=OneTime by default. So, once a DependencyProperty is initialized inside the UserControl, it won't be updated anymore.

    You need to add Mode=OneWay to x:Bind in UpdateBlockControl.

    <StackPanel Orientation="Vertical">
        <TextBlock Text=":-)" />
        <TextBlock Text="{x:Bind AppName, Mode=OneWay}" />
        <TextBlock Text="{x:Bind ImageSource, Mode=OneWay}" />
    </StackPanel>