0

リストビューを含むユーザーコントロールがあるメインウィンドウがあります。ユーザーコントロールには、リストビューのすべての内容をクリップボードにコピーするボタンもあります。これがコピー機能の実装方法です。以下は、ユーザーコントロールの 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 クラスは Dependency プロパティ "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);
    }
}

以下は、リストビューのアイテムのコピーに関連するユーザー コントロール ビューモデルのコードです。

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 関数の送信者オブジェクトは、コンテンツのコピーにさらに使用される usercontrol のリストビューです。すべてのコピー機能は、ユーザー コントロールのボタンで正常に機能します。メインウィンドウでコピー機能のキー バインディングを作成する必要があります。コマンドがMainWindowViewModelで定義されているため、正常に動作するメインウィンドウで他のキーバインディングを作成しましたが、すべてのコピーコマンドのコマンドバインディングはユーザーコントロールのビューモデルにあるため、メインウィンドウビューモデルのキーバインディングのコマンドをユーザーコントロールビューモデルのコマンドバインディングとリンクする際に問題に直面しています. 誰かがこれを手伝ってくれませんか。

前もって感謝します。

4

1 に答える 1