Assuming a code like below,
public class SomeViewModel{
ICommand ReloadCommand{get...}
ICommand SaveCommand{get..}
}
//SomeView.xaml
<SomeCustomControl Reload="ReloadCommand" Save="SaveCommand" /> //NOT SURE HOW??
//SomeCustomContro.xaml
<SomeCustomControl x:Name="someCustomControl">
<Button Command={Binding ElementName=someCustomControl, Path=Reload />
<Button Command={Binding ElementName=someCustomControl, Path=Save />
</SomeCustomControl>
//SomeCustomControl.xaml.cs
..... //NOT SURE HOW TO ALLOW BINDING TO A ICOMMAND ??
In my SomeCustomControl, I need to support "binding of ICommand in xaml". I understand DependencyProperties could be bind like this, but in this case I need to bind ICommand.
EDIT
I can use the DataContext
SomeView
in SomeCustomControl
. There is more logic and separation between the two which I can not dissolve. I 'must' maintain a reference of Reload/Save ICommands
somewhere in my SomeCustomControl
.
Let me get you straight, you want to bind to the Reload
and Save
right?
So that needs creating, declaring and defining two dependency properties ReloadCommandProperty
and SaveCommandProperty
of type ICommand
for SomeCustomControl
.
So assuming that SomeCustomControl
derives from Control
...
public class SomeCustomControl : Control
{
public static DependencyProperty ReloadCommandProperty
= DependencyProperty.Register(
"ReloadCommand",
typeof (ICommand),
typeof (SomeCustomControl));
public static DependencyProperty SaveCommandProperty
= DependencyProperty.Register(
"SaveCommand",
typeof(ICommand),
typeof(SomeCustomControl));
public ICommand ReloadCommand
{
get
{
return (ICommand)GetValue(ReloadCommandProperty);
}
set
{
SetValue(ReloadCommandProperty, value);
}
}
public ICommand SaveCommand
{
get
{
return (ICommand)GetValue(SaveCommandProperty);
}
set
{
SetValue(SaveCommandProperty, value);
}
}
}
After this proper binding to RelodCommand
and SaveCommand
properties will start working...
<SomeCustomControl RelodCommand="{Binding ViewModelReloadCommand}"
SaveCommand="{Binding ViewModelSaveCommand}" />
Create a property that will return your command and bind this property wherever needed.
private ICommand _reloadCommand;
public ICommand ReloadCommand
{
get
{
if(_reloadCommand == null) _reloadCommand = CreateReloadCommand();
return _reloadCommand;
}
}
Change the binding in your code to
<Button Command={Binding ReloadCommand}" />
And bind the custom control DataContext to the view model that contains the commands.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With