尝试在WPF中为自定义控件创建事件时遇到问题。我们的代码如下:
public static readonly RoutedEvent KeyPressedEvent =
EventManager.RegisterRoutedEvent(
"keyPressed", RoutingStrategy.Bubble,
typeof(KeyEventHandler), typeof(Keyboard));
public event KeyEventHandler keyPressed
{
add { AddHandler(KeyPressedEvent, value); }
remove { RemoveHandler(KeyPressedEvent, value); }
}
void btnAlphaClick(object sender, RoutedEventArgs e)
{
var btn = (Button)sender;
Key key = (Key)Enum.Parse(typeof(Key), btn.Content.ToString().ToUpper());
PresentationSource source = null;
foreach (PresentationSource s in PresentationSource.CurrentSources)
{
source = s;
}
RaiseEvent(new KeyEventArgs(InputManager.Current.PrimaryKeyboardDevice, source,0,key));
控件是一个屏幕键盘,我们基本上需要传递给KeyPressedEventArgs给事件的订阅者详细说明按下了什么键(我们找不到太多帮助我们在WPF中使用它,只有winforms)
任何帮助,非常感谢!
答案 0 :(得分:7)
步骤1:将事件处理程序添加到“确定”和“取消”按钮
private void btnOK_Click(object sender, RoutedEventArgs e)
{
}
private void btnCancel_Click(object sender, RoutedEventArgs e)
{
}
在UserControl1.xaml.cs文件中添加公共属性以与主机共享文本框的值
public string UserName
{
get { return txtName.Text; }
set { txtName.Text = value; }
}
声明可以通过Windows窗体订阅的Ok和Cancel按钮的事件。
public event EventHandler OkClick;
public event EventHandler CancelClick;
现在将代码添加到事件处理程序中,以便我们也可以将事件提升为托管。
private void btnOK_Click(object sender, RoutedEventArgs e)
{
if (OkClick != null)
OkClick(this, e);
}
private void btnCancel_Click(object sender, RoutedEventArgs e)
{
if (CancelClick != null)
CancelClick(this, e);
}
第2步:在Windows窗体中处理WPF控件事件
在创建用户控件实例后立即将Handler添加到OKClick
和CancelClick
个事件
_WPFUserControl.OkClick += new EventHandler(OnOkHandler);
_WPFUserControl.CancelClick += new EventHandler(OnCancelHandler);
在处理程序方法中编写代码。在这里,我在OK按钮处理程序中使用UserName
属性,以便显示如何共享值。
protected void OnOkHandler(object sender, EventArgs e)
{
MessageBox.Show("Hello: " +_WPFUserControl.UserName + " you clicked Ok Button");
}
protected void OnCancelHandler(object sender, EventArgs e)
{
MessageBox.Show("you clicked Cancel Button");
}