问题描述
大家好!
我已经进行了用户控制(可以说它很像按钮).当用户至少按下我的控件2秒钟时,我的控件将提供典型的Click事件以及自定义的Press事件(在这种情况下,不会发送click事件).按下事件是通过使用计时器经过的事件来确定的.
问题是,使用控件时,我可以在单击事件中访问我的发件人,但在新闻事件中却收到错误消息调用线程无法访问该对象,因为另一个线程拥有它."我很困惑..
这是我的customcontrol的代码片段
hi all!
I have made user control (could say it is pretty much like button). My control offers typical click event and also custom press event when user has pressed my control atleast 2 seconds (in this case click event is not sent). Press event is determinated by using timer elapsed event.
The problem is that when using my control i can access my sender in click event but in press event i got error "The calling thread cannot access this object because a different thread owns it." Im confused..
Here is codesnippet from my customcontrol
//timerstarts when user presses button, after 2 seconds this will be launced.
private void aTimer_Elapsed(object source, ElapsedEventArgs e)
{
aTimer.Stop();
OnPressEvent();
}
//my Press event
public event EventHandler<eventargs> PressEvent;
private void OnPressEvent()
{
IsPressEventLaunced = true; //this flag prevents click event to be send
// Copy to a temporary variable to be thread-safe.
EventHandler<eventargs> temp = PressEvent;
if (temp != null)
{
temp(this, new EventArgs()); //The problem!! I can send 'this' BUT in client side cannnot use 'sender'
}
}
//my click event
public event RoutedEventHandler Click;
//happens when mouse is released, sends click event unless pressevent is launched
private void myControl_PreviewMouseUp(object sender, MouseButtonEventArgs e)
{
aTimer.Stop();
if (!IsPressEventLaunced)
{
if (null != Click)
Click(sender, e);
}
}</eventargs></eventargs>
这是客户端的摘录
And here is snippet from client side
private void button_PressEvent(object sender, EventArgs e)
{
myControl temp = (myControl )sender as myControl ;
//Here I cannot use sender information
}
private void button_Click(object sender, RoutedEventArgs e)
{
myControl temp = (myControl )sender as myControl;
//Here I can access sender information
}
希望您有想法:)
hope you got idea :)
推荐答案
private void OnPressEvent()
{
if(!Dispatcher.CheckAccess())
{
Dispatcher.Invoke((Action) OnPressEvent, null);
return;
}
IsPressEventLaunced = true; //this flag prevents click event to be send
// Copy to a temporary variable to be thread-safe.
EventHandler<eventargs> temp = PressEvent;
if (temp != null)
{
temp(this, new EventArgs()); //The problem!! I can send 'this' BUT in client side cannnot use 'sender'
}
}
这篇关于WPF UserControl事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!