我有一个mainwindow,其中有一个包含listview的usercontrol。 用户控件也有一个按钮,它将listview的所有内容复制到剪贴板。 这是如何实现复制功能的。下面 是用户控件的XAML的一部分 -将mainwindow视图模型中的KeyBinding命令链接到用户控件的视图模型commandbindings
<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>
的AttachedProperties类持有的依赖属性“化CommandBindings” - 下面的代码 -
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);
}
}
下面是有关复制的用户控件视图模型的代码项目的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);
}
}
在CtrlCCopyCmdExecuted功能发送者对象是在用户控件的列表视图,其在futher使用 复制其内容。 复制所有功能在用户控制按钮上正常工作。 我必须在mainwindow中为复制功能创建一个键绑定。我在mainwindow中创建了其他键绑定,因为这些命令在MainWindowViewModel中定义,但由于copy all命令的命令绑定位于usercontrol的视图模型中,所以我在将mainwindowviewmodel中的键绑定命令与usercontrolviewmodel中的命令绑定。 有人可以帮我解决这个问题。
在此先感谢。
谢谢谢里登。但是我可能在实施这个解决方案时遇到一些问题。 childViewModel没有特定的命令来复制。它使用称为Commandbindings的依赖项属性(请参阅上面的usercontrol xaml和AttachedProperties类)。我有权访问parenViewModel中的childViewModel的Commandbindings。无论如何,我可以用它来执行命令。另外Executed eventhandler中的sender对象应该是listview(复制按钮的commandtarget是listview)。 – rajat