我可以将剪贴板作为命令参数发送吗?

时间:2023-01-11 20:47:20

Using MVVM I have a ViewModel that implements commands. I would like to receive the Clipboard contents as a parameter and do things with it.

使用MVVM我有一个实现命令的ViewModel。我想收到剪贴板内容作为参数并用它做事。

XAML:

    <Button Command="{Binding Path=ClipBoardAction}" 
            CommandParameter="{Binding SomeAwesomeCodeHereToPassCurrentClipboard}" />

c#:

private void ClipBoardAction(object parameter) {
    //parameter is clipboard OR CLIPBOARD DATA like string[]
 }

Is this possible? If so, what do I bind to in the XAML?

这可能吗?如果是这样,我在XAML中绑定什么?

EDIT: Work around so far is to just wire the button to a Click event and put in some code behind glue.

编辑:到目前为止工作只是将按钮连接到Click事件并在胶水后面添加一些代码。

    private void Button_Click(object sender, RoutedEventArgs e) {
        //manually send command to object
        string[] clipboard = Clipboard.GetText().Split(new Char[] { '\n' });
        var but = sender as Button;
        var viewModel = (FooViewModel)but.DataContext;
        if (viewModel.ClipBoardAction.CanExecute(null)){
            viewModel.ClipBoardAction.Execute(clipboard);
        }
    }

1 个解决方案

#1


Since Clipboard class provides clipboard data as methods not properties, and binding can be done with properties only, no you can't do that.

由于Clipboard类提供剪贴板数据作为方法而不是属性,并且只能使用属性进行绑定,否则不能这样做。

Edit

You may hack the problem by implementing a custom converter but I don't think it is much worthy:

您可以通过实现自定义转换器来解决问题,但我认为它不值得:

public class ClipboardConverter : IValueConverter {
    public object Convert(object value, Type targetType, object parameter, 
                  System.Globalization.CultureInfo culture) {
        return Clipboard.GetData(value as string);
    }
    public object ConvertBack(object value, Type targetType, object parameter, 
                  System.Globalization.CultureInfo culture) {
        throw new NotImplementedException();
    }
}

#1


Since Clipboard class provides clipboard data as methods not properties, and binding can be done with properties only, no you can't do that.

由于Clipboard类提供剪贴板数据作为方法而不是属性,并且只能使用属性进行绑定,否则不能这样做。

Edit

You may hack the problem by implementing a custom converter but I don't think it is much worthy:

您可以通过实现自定义转换器来解决问题,但我认为它不值得:

public class ClipboardConverter : IValueConverter {
    public object Convert(object value, Type targetType, object parameter, 
                  System.Globalization.CultureInfo culture) {
        return Clipboard.GetData(value as string);
    }
    public object ConvertBack(object value, Type targetType, object parameter, 
                  System.Globalization.CultureInfo culture) {
        throw new NotImplementedException();
    }
}