Jonathan Allen
Jonathan Allen

Reputation: 70307

WPF: How do I bind to an ICommand defined in a control?

My control has a property that returns an ICommand object. Using XAML, how to I bind a button to it?

Upvotes: 0

Views: 118

Answers (1)

DHN
DHN

Reputation: 4865

Without knowing anything about the relation of the two I would use element binding. E.g.

<YourControl x:Name="CmdSrc" />
<Button Command={Binding ElementName=CmdSrc, Path=CmdProperty} />

You should think about the approach that a control provides a command. It's seems to me some kind of weird. ;)

Regards

EDIT

Ah ok, it was just a hint. Just in case you didn't think about it.

Here is another way to bind your command. I've to admit that I didn't test it. But I think the following should work too.

When the Button is in the control you could also use relative binding.

<YourControl>
  <Button Command={Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type YourControl}}, Path=CmdProperty} />
</YourControl>

Then you don't need a name for the control. I'm avoiding names when ever I can to prevent dirty workarounds in code behind.

Yes, I know it some kind of paranoid. ;)

Upvotes: 5

Related Questions