In a xaml file, how can I use a event handler from another cs file?
For example, I have a button with a click event in a xaml file: < Button x:Name="ButtonFindCoordinate" C开发者_开发百科ontent="Map Coordinate" Click="ButtonFindCoordinate_Click" />
To my knowledge, this ButtonFindCoordinate_Click event handler must be a function from the code behind cs file. Is there any way I can reference an event handler from another cs file in this xaml file (for example, this button is from aa.xaml file, and I have an event handler function saved in bb.cs)? How can I write this code?
Thanks,
Wei
I would say its generally better practice extract the logic of your handler into a separate class then have both click handlers call this same method.
For Example
in A.xaml.cs
private void ButtonFindCoordinate_Click(object sender, EventArgs e)
{
string postCode = CoordinateFinder.FindPostCode(txtButtonFind.Text);
}
and B.xaml.cs
private void OtherButton_Click(object sender, EventArgs e)
{
string postCode = CoordinateFinder.FindPostCode(txtSomeOtherField.Text);
}
and then the CoordinateFinder class could be something like.
public class CoordinateFinder
{
public static string FindPostCode(string coordinates)
{
// shared code here.
}
}
The reason I say it's better practice not 'share' a click handler across classes, is that you want your code to be as readable and maintainable as possible.
Imagine if you come back in a few months and see the click handler from class B calling the click handler from class A - now you have to read the click handler of A to discover what it does.
Furthermore if you (or someone on your team) was to update aa.xaml.cs, they might access fields from aa.xaml which would break bb.cs without their knowledge.
Hope that helps -
Pass the reference of aa.xaml to bb.cs and use the reference to access the event.
精彩评论