Reputation: 3788
In a WPF application, suppose there are 'n'-number of pictures of type image and if on clicking any picture (i.e. of type image), its visibility should collapse. Now a normal way to do this would be to to write the code to collapse for every 'Click' event for every picture.
Is there an alternative way so that the application can understand that whenever any UIelement(picture) of type image is clicked then that particular element(picture) should collapse?
I want to reduce the code, how can I achieve this?
Upvotes: 3
Views: 1958
Reputation: 564413
You can take advantage of the fact that these are Routed Events, and set a single handler on a parent element.
This allows a single event handler to handle all events of the child controls. The OriginalSource
property of the event args will provide the UIElement that was clicked, if, for example, you subscribed to UIElement.MouseLeftButtonDown
or a similar "shared" event.
You would do this by adding, in your XAML, to your container:
<Grid UIElement.MouseLeftButtonDown="CommonClickHandler">
<!-- Your elements here -->
Then, in your code behind:
private void CommonClickHandler(object sender, MouseButtonEventArgs e)
{
Image picture = e.OriginalSource as Image; //OriginalSource is the original element
if (picture != null)
picture.Visibility = Visibility.Collapsed;
}
Upvotes: 3
Reputation: 5689
You can register the method you are using on multiple event handlers and get access to the particular control by using Object sender
parameter and casting it to the type of control you are using.
myControl.Click += new EventHandler(myGenericClickMethod);
public void myGenericClickMethod(Object sender, EventArgs e)
{
Image myImage = (Image) sender;
myImage..Visibility = System.Windows.Visibility.Collapsed;
}
Upvotes: 1
Reputation: 81253
You can add global handler using EventManager.RegisterClassHandler like this -
public MainWindow()
{
InitializeComponent();
EventManager.RegisterClassHandler(typeof(Image), Image.MouseDownEvent,
new RoutedEventHandler(OnMouseDown));
}
private void OnMouseDown(object sender, RoutedEventArgs e)
{
(sender as Image).Visibility = System.Windows.Visibility.Collapsed;
}
Upvotes: 2