xamlwinui-3winuiwindows-community-toolkit

Binding to element item count


I want to have a visibility based on the selecteditems count of a datagrid. However, this doesn't seem to work in winui, but worked fine in WPF?

Converter:

 public object Convert(object value, Type targetType, object parameter, string language)
  {
      if ((int)value == 1)
          return Visibility.Visible;
      else
          return Visibility.Collapsed;
  }

Binding:

   Visibility="{Binding ElementName=DataGrid,Path=SelectedItems.Count, 
     Converter={StaticResource Converter}}"

Also tried with x:Bind:

  Visibility="{x:Bind DataGrid.SelectedItems.Count, 
    Converter={StaticResource CountToVisibilityConverter}}"

It seems to me that the property isn't updated. If I put a breakpoint in the converter it is only called at the intial stage.


Solution

  • This is because that Count is just plain property and does not notify the UI when is changed.

    One way to achieve this is by just using the SelectionChanged event and check the SelectedItems.Count.

    Another way is by creating a custom DataGrid with a DependencyProperty. For example:

    public class DataGridEx : DataGrid
    {
        public static readonly DependencyProperty SelectedItemsCountProperty =
            DependencyProperty.Register(
                nameof(SelectedItemsCount),
                typeof(int),
                typeof(DataGridEx),
                new PropertyMetadata(0));
    
        public DataGridEx()
        {
            SelectionChanged += (s, e) =>
            {
                SelectedItemsCount = SelectedItems.Count;
            };
        }
    
        public int SelectedItemsCount
        {
            get => (int)GetValue(SelectedItemsCountProperty);
            set => SetValue(SelectedItemsCountProperty, value);
        }
    }
    

    and use it like this:

    <local:DataGridEx x:Name="DataGridExControl" .../>
    
    <TextBlock Text="{x:Bind DataGridExControl.SelectedItemsCount, Mode=OneWay" />