I have a mainwindow inside which there is a usercontrol which contains a listview. User control also has a button which copies all the contents of listview to clipboard. This is how the copy functionality has been implemented. below is a part of xaml of usercontrol -
<Button Command="Copy"
CommandTarget="{Binding ElementName=testCodeView}"
CommandParameter="Copy"
</Button>
<ListView x:Name="testCodeView"
ItemsSource="{Binding Products}" BorderThickness="0" Grid.Row="1"
ItemTemplate="{StaticResource testViewTemplate}"
ItemContainerStyle="{StaticResource testCodesListItem}"
infra:AttachedProperties.CommandBindings ="{Binding CommandBindings}">
</ListView>
The AttachedProperties class holds the Dependency property "CommandBindings" - below is the code -
public class AttachedProperties
{
public static DependencyProperty CommandBindingsProperty =
DependencyProperty.RegisterAttached("CommandBindings", typeof(CommandBindingCollection), typeof(AttachedProperties),
new PropertyMetadata(null, OnCommandBindingsChanged));
public static void SetCommandBindings(UIElement element, CommandBindingCollection value)
{
if (element != null)
element.SetValue(CommandBindingsProperty, value);
}
public static CommandBindingCollection GetCommandBindings(UIElement element)
{
return (element != null ? (CommandBindingCollection)element.GetValue (CommandBindingsProperty) : null);
}
}
Below is the usercontrol viewmodel's code related to copying the items of listview.
public class UserControlViewModel : INotifyPropertyChanged
{
public CommandBindingCollection CommandBindings
{
get
{
if (commandBindings_ == null)
{
commandBindings_ = new CommandBindingCollection();
}
return commandBindings_;
}
}
public UserControlViewModel
{
CommandBinding copyBinding = new CommandBinding(ApplicationCommands.Copy,
this.CtrlCCopyCmdExecuted, this.CtrlCCopyCmdCanExecute);
// Register binding to class
CommandManager.RegisterClassCommandBinding(typeof(UserControlViewModel), copyBinding);
this.CommandBindings.Add(copyBinding);
}
private void CtrlCCopyCmdExecuted(object sender, ExecutedRoutedEventArgs e)
{
copyToclipboard_.CtrlCCopyCmdExecuted(sender, e);
}
}
The sender object in CtrlCCopyCmdExecuted function is the listview in usercontrol which is futher used in copying its contents. The copy all functionality works fine with the button on user control. I have to create a key binding for copy functionality in mainwindow. I have created other keybindings in mainwindow which works fine as the commands are defined in MainWindowViewModel, but since the commandbindings of the copy all command are in the usercontrol's view model, I am facing problems in linking command of keybinding in mainwindowviewmodel with the commandbinding in usercontrolviewmodel. Can Someone help me out with this.
Thanks in advance.