开发者

How can I accept pastes from the clipboard in my UserControl?

开发者 https://www.devze.com 2023-01-11 06:11 出处:网络
I\'ve got a UserControl that, oddly enough, bundles a bunch of other controls and logic into a tidy little package.It has a Text property that accepts a string and does magic, displaying the results f

I've got a UserControl that, oddly enough, bundles a bunch of other controls and logic into a tidy little package. It has a Text property that accepts a string and does magic, displaying the results for the user. Awesome.

I get that text from a TextBox. The user pastes开发者_StackOverflow社区 text from the clipboard in the textbox, which is bound to a DP on my UserControl.

What I'd like to do is cut out the middle man and accept pastes within my UserControl.

I've already tried using the DataObject.Pasting attached event, but that appears not to work.

How do you do it?


Answered my own question with my current solution, but honestly it "smells". If anybody has a better answer, please add it and if it works and is better I'll select it.


My brain fired. Command Bindings. Now I know when someone tries to paste and can take it from there.

XAML:

<UserControl.CommandBindings>
    <CommandBinding
        Command="Paste"
        Executed="CommandBinding_Executed"/>
</UserControl.CommandBindings>

(excuse the bad code; trying to get this working for now) And the event handler:

try
{
    var text = Clipboard.GetData(DataFormats.Text) as string;
    if (string.IsNullOrWhiteSpace(text))
        return;
    Lines = new Lines(text);
    e.Handled = true;
}
catch (Exception ex)
{
    MessageBox.Show(ex.Message, "Paste failed", MessageBoxButton.OK);
}

This smells, IMHO. But I'm not sure how else to handle this.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号