Search code examples
c#wpfmvvmcommandbindingcommandparameter

WPF Command: parameter from user control


I'm in my MainWindowView.xaml. It includes a usercontrol.

I'm trying to set a command with a parameter. This parameter is the selected row of a gridControl (devexpress item).

I have tried two binding, both wrong (they don't find the parameter):

<Button Command="{Binding DeleteCommand}" CommandParameter="{Binding Path=lst1, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type uc:ucImpianti}}}" Style="{DynamicResource BtnToolBar}"/>

and

<Button Command="{Binding DeleteCommand}" CommandParameter="{Binding ElementName=lst1, Path=FocusedRow}" Style="{DynamicResource BtnToolBar}"/>

How have I to write the binding to pass the selected row of a gridControl in a UC?

My command defition is:

public ICommand DeleteCommand { get; private set; }
private void DeleteRecord(object parameter)
{
    Debug.WriteLine(parameter);
}
[...]
DeleteCommand = new DelegateCommand<object>(DeleteRecord, CanAlways);

Solution

  • It is customary in WPF to data bind a collection of a certain type to the ItemsSource property and a property of the type of object in the collection to the SelectedItem property (it makes no difference that this example uses a ListBox):

    <ListBox ItemsSource="{Binding YourCollection}" 
        SelectedItem="{Binding YourSelectedItem}" ... />
    

    With this set up, you can data bind directly to the YourSelectedItem property from the CommandParameter property:

    <Button Command="{Binding DeleteCommand}" CommandParameter="{Binding YourSelectedItem}"
        Style="{DynamicResource BtnToolBar}" />