這是一個線程問題。我們必須獲得正確的線程並通過代表執行。
我正在更新我的屬性,通過計時器每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