JBe*_*gle 3 c# wpf events wpf-controls
尝试在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));
Run Code Online (Sandbox Code Playgroud)
该控件是一个屏幕键盘,我们基本上需要传递给KeyPressedEventArgs给事件的订阅者详细说明按下了什么键(我们找不到太多帮助我们在WPF中使用它,只有winforms).
任何帮助,非常感谢!
步骤1:将事件处理程序添加到"确定"和"取消"按钮
private void btnOK_Click(object sender, RoutedEventArgs e)
{
}
private void btnCancel_Click(object sender, RoutedEventArgs e)
{
}
Run Code Online (Sandbox Code Playgroud)
在UserControl1.xaml.cs文件中添加公共属性以与主机共享文本框的值
public string UserName
{
get { return txtName.Text; }
set { txtName.Text = value; }
}
Run Code Online (Sandbox Code Playgroud)
声明可以通过Windows窗体订阅的Ok和Cancel按钮的事件.
public event EventHandler OkClick;
public event EventHandler CancelClick;
Run Code Online (Sandbox Code Playgroud)
现在将代码添加到事件处理程序,以便我们也可以将事件提升为主机.
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);
}
Run Code Online (Sandbox Code Playgroud)
第2步:在Windows窗体中处理WPF控件事件
在创建用户控件的实例后立即添加处理程序OKClick和CancelClick事件
_WPFUserControl.OkClick += new EventHandler(OnOkHandler);
_WPFUserControl.CancelClick += new EventHandler(OnCancelHandler);
Run Code Online (Sandbox Code Playgroud)
在处理程序方法中编写代码.在这里,我UserName在OK按钮处理程序中使用该属性,以便显示如何共享值.
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");
}
Run Code Online (Sandbox Code Playgroud)
参考:http: //a2zdotnet.com/View.aspx?Id = 79