WindowsCommunityToolkit icon indicating copy to clipboard operation
WindowsCommunityToolkit copied to clipboard

Button Command doesn't getting executed in DataGridTemplateColumn

Open Reza-Noei opened this issue 2 years ago • 6 comments

Describe the bug

I have a DataGrid defined as below:

<toolkit:DataGrid x:Name="dataGrid"
                  ItemsSource="{x:Bind ViewModel.Tests, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"
                  MinHeight="500"
                  AreRowDetailsFrozen="False"
                  AreRowGroupHeadersFrozen="True"
                  AutoGenerateColumns="False"
                  CanUserSortColumns="True"
                  ColumnHeaderHeight="40"
                  FrozenColumnCount="0"
                  RowDetailsVisibilityMode="Collapsed"
                  RowGroupHeaderPropertyNameAlternative="Range">
    <toolkit:DataGrid.Columns>
        <toolkit:DataGridTemplateColumn Header="Records (count)" Tag="RecordsCount" Width="150">
            <toolkit:DataGridTemplateColumn.CellTemplate>
                <DataTemplate>
                    <TextBlock HorizontalAlignment="Center" VerticalAlignment="Center" Text="{Binding RecordsCount}"/>
                </DataTemplate>
            </toolkit:DataGridTemplateColumn.CellTemplate>
        </toolkit:DataGridTemplateColumn>
        <toolkit:DataGridTemplateColumn  Width="184">
            <toolkit:DataGridTemplateColumn.CellTemplate>
                <DataTemplate>
                    <StackPanel HorizontalAlignment="Right" Orientation="Horizontal">
                        <!-- Click event works but command doesn't getting executed -- >
                        <Button Width="40" Height="40" 
                                Command="{Binding ViewModel.DeleteTestCommand, ElementName=testPage}"
                                CommandParameter="{Binding Id}">
                        </Button>
                        <Button Width="40" Height="40"
                                Command="{Binding ViewModel.EditTestCommand, ElementName=testPage}"
                                CommandParameter="{Binding Id}">
                        </Button>
                    </StackPanel>
                </DataTemplate>
            </toolkit:DataGridTemplateColumn.CellTemplate>
        </toolkit:DataGridTemplateColumn>
    </toolkit:DataGrid.Columns>
</toolkit:DataGrid>

As you can see, I have two button with commands EditTestCommand and DeleteTestCommand. These commands aren't working when user clicks on those buttons.

I can use Button's click event instead. But I don't know why Commands aren't working.

public partial class TestsPageViewModel : ObservableRecipient
{
    public IRelayCommand<int> EditTestCommand { get; }

    public IRelayCommand<int> DeleteTestCommand { get; }

    public TestsPageViewModel(ITestsQueryService testsQueryService, INavigationService navigationService)
    {
        EditTestCommand = new RelayCommand<int>(EditTest);
        DeleteTestCommand = new RelayCommand<int>(DeleteTest);
       
        Tests = new ObservableCollection<TestModel>(); //(Some tests here);
    }

    public void DeleteTest(int id)
    {
        //var test = Tests.First(P => P.Id == id);
    }

    public void EditTest(int id)
    {
        //var test = Tests.First(P => P.Id == id);
    }

    public ObservableCollection<TestModel> Tests 
    { 
        get => _tests;
        set => SetProperty(ref _tests, value); 
    }
}

and TestModel contains:

public int Id { get; set; }
public int RecordCount { get; set; } , ....

As I mentioned in the Xaml Click event works for buttons but Commands aren't working at all.

In my Page class I have a property of Type PageViewModel (named ViewModel) which contains an ObservableCollection of type TestModel

Regression

"CommunityToolkit.WinUI.UI.Controls.DataGrid" Version="7.1.2"

Reproducible in sample app?

  • [X] This bug can be reproduced in the sample app.

Steps to reproduce

Run whatever I've attached in the bug description.

Expected behavior

I expected to see button commands working.

Screenshots

No response

Windows Build Number

  • [ ] Windows 10 1809 (Build 17763)
  • [ ] Windows 10 1903 (Build 18362)
  • [ ] Windows 10 1909 (Build 18363)
  • [X] Windows 10 2004 (Build 19041)
  • [ ] Windows 10 20H2 (Build 19042)
  • [ ] Windows 10 21H1 (Build 19043)
  • [ ] Windows 11 21H2 (Build 22000)
  • [ ] Other (specify)

Other Windows Build number

No response

App minimum and target SDK version

  • [X] Windows 10, version 1809 (Build 17763)
  • [ ] Windows 10, version 1903 (Build 18362)
  • [ ] Windows 10, version 1909 (Build 18363)
  • [ ] Windows 10, version 2004 (Build 19041)
  • [ ] Other (specify)

Other SDK version

No response

Visual Studio Version

2022

Visual Studio Build Number

17.6.2

Device form factor

Desktop

Nuget packages

Additional context

No response

Help us help you

Yes, but only if others can assist.

Reza-Noei avatar Aug 10 '23 09:08 Reza-Noei

Hello Reza-Noei, thank you for opening an issue with us!

I have automatically added a "needs triage" label to help get things started. Our team will analyze and investigate the issue, and escalate it to the relevant team if possible. Other community members may also look into the issue and provide feedback 🙌

ghost avatar Aug 10 '23 09:08 ghost

This issue has been marked as "needs attention 👋" due to no activity for 15 days. Please triage the issue so the fix can be established.

ghost avatar Aug 25 '23 13:08 ghost

I am facing the exact same issue when using buttons and commands in a DataGridTemplateColumn. And when I use the Button's click event, everything works fine. However, the click property triggered a "XAML parsing error" only when I try to add an item to an empty datagrid. But when I remove the property, the issue disappears. And if the button is in RowDetailsTemplate with the click property, there are no issues either.

NathanQuellec avatar Aug 25 '23 17:08 NathanQuellec

@Reza-Noei @NathanQuellec

I also faced the same issue where the button command was not invoked. Found a workaround solution for this.

Workaround Solution :

  1. Create a attached property to find the parent element based on type.
  2. Use the attached property in the button and specify the type as Datagrid.
  3. Boom! command will be invoked.
  4. If parameter needs to be passed, we will be needed to add a parent control and get its datagrid.

Attached Property :

namespace Win.Ui.Controls.AttachedProperties
{
    public static class AncestorSource
    {
        public static readonly DependencyProperty AncestorTypeProperty = DependencyProperty.RegisterAttached("AncestorType", typeof(Type), typeof(AncestorSource), new PropertyMetadata(default(Type), OnAncestorTypeChanged));

        public static void SetAncestorType(FrameworkElement element, Type value) => element.SetValue(AncestorTypeProperty, value);

        public static Type GetAncestorType(FrameworkElement element) => (Type)element.GetValue(AncestorTypeProperty);

        private static void OnAncestorTypeChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            FrameworkElement target = (FrameworkElement)d;
            if (target.IsLoaded)
            {
                SetDataContext(target);
            }
            else
            {
                target.Loaded += OnTargetLoaded;
            }
        }

        private static void OnTargetLoaded(object sender, RoutedEventArgs e)
        {
            FrameworkElement target = (FrameworkElement)sender;
            target.Loaded -= OnTargetLoaded;
            SetDataContext(target);
        }

        private static void SetDataContext(FrameworkElement target)
        {
            Type ancestorType = GetAncestorType(target);
            if (ancestorType != null)
            {
                target.DataContext = FindParent(target, ancestorType);
            }
        }

        private static object FindParent(DependencyObject dependencyObject, Type ancestorType)
        {
            DependencyObject parent = VisualTreeHelper.GetParent(dependencyObject);
            if (parent == null)
            {
                return null;
            }

            if (ancestorType.IsAssignableFrom(parent.GetType()))
            {
                return parent;
            }

            return FindParent(parent, ancestorType);
        }
    }
}

In Xaml,

  1. Add namespace for the attached property

xmlns:ansestorSource="using:Win.Ui.Controls.AttachedProperties"

  1. Your DataGridTemplateColumn should be :
<toolkit:DataGridTemplateColumn  Width="184">
    <toolkit:DataGridTemplateColumn.CellTemplate>
        <DataTemplate>
            <StackPanel x:Name="Parent_StackPanel" HorizontalAlignment="Right" Orientation="Horizontal">
                <!-- Click event works but command doesn't getting executed -- >
                <Button ansestorSource:AncestorType="toolkit:DataGrid" Width="40" Height="40" 
                        Command="{Binding DataContext.DeleteTestCommand}"
                        CommandParameter="{Binding ElementName="Parent_StackPanel", Path="DataContext"}">
                </Button>
                <Button ansestorSource:AncestorType="toolkit:DataGrid" Width="40" Height="40"
                        Command="{Binding DataContext.EditTestCommand}"
                        CommandParameter="{Binding ElementName="Parent_StackPanel", Path="DataContext"}">
                </Button>
            </StackPanel>
        </DataTemplate>
    </toolkit:DataGridTemplateColumn.CellTemplate>
</toolkit:DataGridTemplateColumn>

Hope it helps!

AkilanRagavaswamy avatar Feb 16 '24 12:02 AkilanRagavaswamy

Thanks @AkilanRagavaswamy . This works!

Harinath-2000 avatar Feb 16 '24 12:02 Harinath-2000

Thanks @AkilanRagavaswamy too ! This works very good!

swat199538 avatar Aug 12 '24 10:08 swat199538