Quantcast
Channel: Windows Presentation Foundation (WPF) forum
Viewing all articles
Browse latest Browse all 18858

Is it possible to add a custom event handler in code-behind? Or is it limited to XAML?

$
0
0

I tried adding a custom event handler to a collection of textboxes on my WPF app as follows (similar to how I did in winform) -- but error'd out. So I added this custom event handler in the xaml, and that worked.

public MainWindow()
{
   InitializeComponent();
   textBoxes = new TextBox[] { txtrowID, txtFirstName, txtLastName, txtAddress, txtPhone, txtNationality };

   foreach (TextBox txt in textBoxes)
   {
      txt.TextChanged += new TextChangedEventHandler(Text_Changed);
   }
}

//--my custom Event handler
private void Text_Changed(object sender, TextChangedEventArgs e)
{ 
   if(((TextBox)sender).Text != "")
      btnUpdate.IsEnabled = true;
}
//--this err'd out

So I added the custom event handler in the XAML

... TextChanged="Text_Changed"/>

and commented out the foreach(...) loop in the code-behind.  This worked.  The question is if it is possible to add event handlers in code-behind in WPF -- and -- are there cases where it would be preferred to add event handlers in code-behind instead of the XAML? 


Rich P


Viewing all articles
Browse latest Browse all 18858

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>