michael
michael

Reputation: 15282

WPF - Custom Control + ICommand (How do I Implement this)?

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?
    }

Upvotes: 3

Views: 5307

Answers (2)

Matt West
Matt West

Reputation: 2944

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

Upvotes: 5

SergioL
SergioL

Reputation: 4963

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,

Upvotes: 3

Related Questions