【发布时间】:2013-10-31 17:03:09
【问题描述】:
我有一个主窗口,里面有一个包含列表视图的用户控件。 用户控件还有一个按钮,可以将 listview 的所有内容复制到剪贴板。 这就是复制功能的实现方式。 下面是用户控件 xaml 的一部分 -
<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);
}
}
下面是usercontrol viewmodel复制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函数中的sender对象是usercontrol中的listview,在 复制其内容。 复制所有功能可与用户控件上的按钮正常工作。 我必须在主窗口中为复制功能创建一个键绑定。我在主窗口中创建了其他键绑定,这些键绑定工作正常,因为命令是在 MainWindowViewModel 中定义的,但是由于复制所有命令的命令绑定在用户控件的视图模型中,我在将主窗口视图模型中的键绑定命令与 usercontrolviewmodel 中的命令绑定链接时遇到问题. 有人可以帮我解决这个问题。
提前致谢。
【问题讨论】:
标签: c# wpf mvvm key-bindings