Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8180425
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 7, 20262026-06-07T00:12:42+00:00 2026-06-07T00:12:42+00:00

I’m having trouble getting the CanExecute method of my command to work property. I’ve

  • 0

I’m having trouble getting the CanExecute method of my command to work property. I’ve bound a command to a button that is inside of a DataGrid. I’ve bound the CommandParameter to the button’s DataContext, which happens to be a record for a row in the DataGrid.

What I expect to happen is for the CanExecute method to be re-evaluated when the CommandParameter binding changes, which in this case would be the row’s DataContext property being set. But instead of evaluating the CanExecute method against the row data, it looks like the CanExecute method is being evaluated before the row gets its DataContext and it is never re-evaluated after the DataContext has been updated.

Can you tell me how to get the CanExecute method of my command to be evaluated against each row’s DataContext?

I’ve created a sample application to demonstrate my problem. Here’s the code:

The code-behind for the MainWindow.xaml

public partial class MainWindow : Window
{
    public ObservableCollection<LogRecord> Records { get; private set; }
    public ICommand SignOutCommand { get; private set; }
    public MainWindow()
    {
        InitializeComponent();
        DataContext = this;
        Records = new ObservableCollection<LogRecord>();
        SignOutCommand = new SignOutCommand();
        CreateDemoData();
    }
    private void CreateDemoData()
    {
        for (int i = 0; i < 5; i++)
        {
            Records.Add(new LogRecord());
        }
    }
}

public class LogRecord : INotifyPropertyChanged
{
    private DateTime _EntryTime;
    public DateTime EntryTime
    {
        get { return _EntryTime; }
        set
        {
            if (_EntryTime == value) return;
            _EntryTime = value;
            RaisePropertyChanged("EntryTime");
        }
    }

    private DateTime? _ExitTime;
    public DateTime? ExitTime
    {
        get { return _ExitTime; }
        set 
        {
            if (_ExitTime == value) return;
            _ExitTime = value;
            RaisePropertyChanged("ExitTime");
        }
    }

    public LogRecord()
    {
        EntryTime = DateTime.Now;
    }

    #region Implementation of INotifyPropertyChanged

    public event PropertyChangedEventHandler PropertyChanged;

    public void RaisePropertyChanged(string propertyName)
    {
        if (PropertyChanged != null) PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
    }

    #endregion
}

public class SignOutCommand : ICommand
{
    #region Implementation of ICommand

    public void Execute(object parameter)
    {
        var record = parameter as LogRecord;
        if (record == null) return;
        record.ExitTime = DateTime.Now;
    }

    public bool CanExecute(object parameter)
    {
        var record = parameter as LogRecord;
        return record != null && !record.ExitTime.HasValue;
    }

    public event EventHandler CanExecuteChanged;

    #endregion
}

The XAML for MainWindow.xaml

<Window x:Class="Command_Spike.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="MainWindow"
    Width="525"
    Height="350">
<DataGrid ItemsSource="{Binding Path=Records}" IsReadOnly="True" AutoGenerateColumns="False">
    <DataGrid.Columns>
        <DataGridTextColumn Header="Entry Time" Binding="{Binding Path=EntryTime}" />
        <DataGridTextColumn Header="Exit Time" Binding="{Binding Path=ExitTime}" />
        <DataGridTemplateColumn>
            <DataGridTemplateColumn.CellTemplate>
                <DataTemplate>
                    <Button Command="{Binding RelativeSource={RelativeSource Mode=FindAncestor,
                                                                             AncestorType=Window},
                                              Path=DataContext.SignOutCommand}"
                            CommandParameter="{Binding}"
                            Content="Sign Out" />
                </DataTemplate>
            </DataGridTemplateColumn.CellTemplate>
        </DataGridTemplateColumn>
    </DataGrid.Columns>
</DataGrid>

If you load up the example code, you can see that all of the Sign Out buttons are disabled because in each row, the CanExecute method is receiving null as the parameter instead of the row-specific data that I want. If this sample were working properly, all of the buttons would be enabled initially and would only disable after a value in the Exit Time column was set.

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-07T00:12:43+00:00Added an answer on June 7, 2026 at 12:12 am

    You are not setting up the custom command correctly. In your current example, you don’t need to create a command manually that implements ICommand, you simply need to create a Routed or RoutedUI command and wire up the appropriate handlers. Remove your SignOutCommand object, then modify your Window code like the following:

    public partial class MainWindow: Window
    {
        public ObservableCollection<LogRecord> Records { get; private set; }
        public static RoutedUICommand SignOutCommand { get; private set; }
    
        public MainWindow()
        {
            InitializeComponent();
            DataContext = this;
            Records = new ObservableCollection<LogRecord>();
            CreateDemoData();
    
            SignOutCommand = new RoutedUICommand();
            CommandBinding cb = new CommandBinding(SignOutCommand, OnSignOut, OnCanSignOut);
            this.CommandBindings.Add(cb);
        }
    
    
        private void CreateDemoData()
        {
            for (int i = 0; i < 5; i++)
            {
                Records.Add(new LogRecord());
            }
        }
    
        private void OnCanSignOut(object sender, CanExecuteRoutedEventArgs e)
        {
            var record = e.Parameter as LogRecord;
            e.CanExecute = record != null && !record.ExitTime.HasValue;
    
        }
    
        private void OnSignOut(object sender, ExecutedRoutedEventArgs e)
        {
            var record = e.Parameter as LogRecord;
            if (record == null) return;
            record.ExitTime = DateTime.Now;
        }
    }
    

    then, modify your DataTemplate like follows (basically, just remove the DataContext from the Path):

    <dg:DataGridTemplateColumn>
      <dg:DataGridTemplateColumn.CellTemplate>
        <DataTemplate>
           <Button Command="{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=Window}, Path=SignOutCommand}" CommandParameter="{Binding}" Content="Sign Out" />
        </DataTemplate>
      </dg:DataGridTemplateColumn.CellTemplate>
    </dg:DataGridTemplateColumn>
    

    Using this approach, your sign out button will be correctly enabled when the DataContext is set.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

link Im having trouble converting the html entites into html characters, (&# 8217;) i
I'm parsing an RSS feed that has an &#8217; in it. SimpleXML turns this
I'm having trouble keeping the paragraph square between the quote marks. In firefox the
That's pretty much it. I'm using Nokogiri to scrape a web page what has
I have a string like this: La Torre Eiffel paragonata all&#8217;Everest What PHP function
I've got a string that has curly quotes in it. I'd like to replace
I have a French site that I want to parse, but am running into
I am doing a simple coin flipping experiment for class that involves flipping a
We're building an app, our first using Rails 3, and we're having to build
I need a function that will clean a strings' special characters. I do NOT

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.