While you certainly can do things like Clipboard.SetText and Clipboard.GetText in your VM, if you are an MVVM purist (like me), then I would recommend creating a ClipboardService (with an appropriate interface, so you can mock it in unit tests). Something like the following:
using System.Windows;
public class ClipboardService : IClipboardService
{
public void SetText(string value)
{
Clipboard.SetText(value);
}
public string GetText()
{
return Clipboard.GetText();
}
}
Run Code Online (Sandbox Code Playgroud)
Then you can reference it as a property in your VM like so:
public IClipboardService ClipboardService { get; set; }
Run Code Online (Sandbox Code Playgroud)
And either set it directly as a property or include it in your constructor:
public FooViewModel(IClipboardService service) {
ClipboardService = service;
}
Run Code Online (Sandbox Code Playgroud)
And when you need it, instead of calling Clipboard.SetText directly, you can use ClipboardService.SetText instead. And you can (as mentioned before) mock it in unit tests. So, if you use Moq (like I do), you could have something like:
Mock<IClipboardService> clipMock = new Mock<IClipboardService>();
clipMock.Setup(mock => mock.GetText(It.IsAny<string>())).Returns("Foo");
Run Code Online (Sandbox Code Playgroud)
And instantiate your VM like so:
var fooVm = new FooViewModel(clipMock.Object);
Run Code Online (Sandbox Code Playgroud)
And so on.
I realize this is an ancient post, but I was looking for some best practices on Clipboards and MVVM, made my own decision while reading this post and decided to share. Hope somebody finds it useful. :-)
| 归档时间: |
|
| 查看次数: |
3048 次 |
| 最近记录: |