Question

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?

Was it helpful?

Solution

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;
}

OTHER TIPS

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;
    }

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;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top