这是一个线程问题。我们必须获得正确的线程并通过代表执行。
我正在更新我的属性,通过计时器每500毫秒流逝。下面是代码:
public delegate void ClipboarDelegate();
ClipboarDelegate clipboardDelegate = null;
void clipboardTimer_Elapsed(object sender, ElapsedEventArgs e)
{
if (clipboardDelegate == null)
clipboardDelegate = ClipboarDelegateMethod;
//Here we get the right thread, most probably the application thread
Application.Current.Dispatcher.BeginInvoke(clipboardDelegate);
}
public void ClipboarDelegateMethod()
{
try
{
if (Clipboard.ContainsData(DataFormats.Text))
{
//It's important to lock this section
lock (ClipboardString)
{
ClipboardString = Clipboard.GetData(DataFormats.Text) as string;
}
}
}
catch
{ }
}
而且我做了一个正确的DependencyProperty与ClipboardString:
public static readonly DependencyProperty ClipboardStringDP =
DependencyProperty.Register("ClipboardString",
typeof(string),
typeof(MainWindow),
new UIPropertyMetadata(string.Empty));
public string ClipboardString
{
get { return (string)this.GetValue(ClipboardStringDP); }
set { this.SetValue(ClipboardStringDP, value); }
}
这样,它可以绑定到我的XAML文本框假设我的控制或窗口x:Name="_this"
:
<TextBox Name="ClipBoardTextBox"
DataContext="{Binding ElementName=_this}"
Text="{Binding Path=ClipboardString, Mode=OneWay}"/>
你怎么把数据放在剪贴板? – 2009-02-06 01:03:59
剪贴板上的数据是“文本”,而不是图形,音频或其他数据? – JMD 2009-02-06 01:07:27