WPF - Events from inside User Control
we have a problem when trying开发者_StackOverflow中文版 to create events for a custom control in WPF. We have our code like this:
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));
The control is an on screen keyboard, and we basically need to pass out to the KeyPressedEventArgs to the subscribers to the event detailing what key was pressed (we can't find much that helps us with this in WPF, only winforms).
Any help, greatly appreciated!
Step 1: Add Event Handler to OK and Cancel Button
private void btnOK_Click(object sender, RoutedEventArgs e)
{
}
private void btnCancel_Click(object sender, RoutedEventArgs e)
{
}
Add the public property in the UserControl1.xaml.cs file to share the value of the textbox with the host
public string UserName
{
get { return txtName.Text; }
set { txtName.Text = value; }
}
Declare the Events for Ok and Cancel Buttons which can be subscribed by Windows Form.
public event EventHandler OkClick;
public event EventHandler CancelClick;
Now add the code to the event handler so that we can raise the event to host also.
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);
}
Step 2: Handle the WPF Control Event in Windows Form
Add Handler to OKClick
and CancelClick
Events just after creating the instance of the user control
_WPFUserControl.OkClick += new EventHandler(OnOkHandler);
_WPFUserControl.CancelClick += new EventHandler(OnCancelHandler);
Write code in the handler method. Here I user the UserName
property in the OK button handler so show the how to share the values also.
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");
}
Reference: http://a2zdotnet.com/View.aspx?Id=79
精彩评论