3

Basically, I have a custom control FooControl.

public class FooControl : ItemsControl
{
    //Code
}

I need to add some event handling, but rather than using a RoutedEvent I'd much more prefer to use Commanding instead. I'm not really sure how to go about doing this though. If I want it so that when Bar1Property (DependencyProperty) changes it raises the Execute associated execute property. I looked at the ButtonBase code through .NET Reflector and wow, that looks overly complicated. Is adding a command this complex?? Obviously I'd also have to make it so that my control enables/disables certain parts of itself depending on if the CanExecuteChanged is altered or not. But I guess that's another portion.

Here is my OnBar1Changed function so far...

    private static void OnBar1Changed(DependencyObject obj, DependencyPropertyChangedEventArgs e)
    {
        FooControl element = (FooControl)obj;
        //What to do here?
    }
michael
  • 14,844
  • 28
  • 89
  • 177

2 Answers2

5

It sounds like by the way you are asking your question, you want to support commanding in your custom control (like for example Button supports). To do this you I recommend looking at how ICommandSource is implemented. Microsoft gives a great walk through on how you can implement it yourself:

http://msdn.microsoft.com/en-us/library/ms748978.aspx

Matt West
  • 2,874
  • 1
  • 19
  • 13
  • Yes, this is what I was looking for... a default Command for my custom control. I looked at ButtonBase and it was chaotic how much of it is for the ICommandSource. – michael May 09 '11 at 20:16
  • Sorry I'm not sure I understand this - are you asking me a question or are you just saying that I answered your question with the article? If you are asking how much of ButtonBase is for ICommandSource it would be all the pieces shown in that article. Those are what you need to implement. – Matt West May 09 '11 at 22:41
  • 1
    The comment wasn't a question, just a statement about how chaotic ButtonBase is. – michael May 10 '11 at 01:01
3

At the simplest level, all you really need is something like:

FooControl element = obj as FooControl;
if (element == null) return;

if (element.MyCommand != null && element.CanExecute(this.CommandParameter) 
{
  element.MyCommand.Execute(this.CommandParameter);
}

You'd have to create Dependency Properties for both the Command and the CommandParameter, as well.

Hope that helps,

SergioL
  • 4,905
  • 3
  • 26
  • 30
  • Note that `CommandParameter` isn't mandatory, nor is checking `CanExecute`. It's probably best practice, especially if you are expecting others to reuse your control. But if you don't need them, you can just execute the command directly. – Hugh W Mar 13 '23 at 04:26