Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Button Command doesn't getting executed in DataGridTemplateColumn #4924

Open
3 of 14 tasks
Reza-Noei opened this issue Aug 10, 2023 · 5 comments
Open
3 of 14 tasks

Button Command doesn't getting executed in DataGridTemplateColumn #4924

Reza-Noei opened this issue Aug 10, 2023 · 5 comments
Labels
bug 🐛 An unexpected issue that highlights incorrect behavior DataGrid 🔠 Issues on DataGrid control

Comments

@Reza-Noei
Copy link

Reza-Noei commented Aug 10, 2023

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?

  • 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)
  • 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

  • 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 Reza-Noei added the bug 🐛 An unexpected issue that highlights incorrect behavior label Aug 10, 2023
@ghost ghost added the needs triage 🔍 label Aug 10, 2023
@ghost
Copy link

ghost commented Aug 10, 2023

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 ghost added the needs attention 👋 label Aug 25, 2023
@ghost
Copy link

ghost commented Aug 25, 2023

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.

@NathanQuellec
Copy link

NathanQuellec commented Aug 25, 2023

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.

@AkilanRagavaswamy
Copy link

AkilanRagavaswamy commented Feb 16, 2024

@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!

@Harinath-2000
Copy link

Thanks @AkilanRagavaswamy . This works!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug 🐛 An unexpected issue that highlights incorrect behavior DataGrid 🔠 Issues on DataGrid control
Projects
None yet
Development

No branches or pull requests

5 participants