B
B
BadCats2017-07-14 14:08:38
WPF
BadCats, 2017-07-14 14:08:38

Creating an attached event?

There is a line

sp.AddHandler(Button.Click , new RoutedEventHandler(DoSomething));

- where sp is the StackPanel -
<StackPanel Name="sp" Width="{Binding ElementName=MainGrid, Path=ActualWidth}" Height="{Binding ElementName=MainGrid, Path=ActualHeight}" >

DoSomething - handler method -
private void DoSomething(object sender, RoutedEventArgs e)
        {
            if(e.OriginalSource==BTN)
            {
                BTN.Content = ContentControl.ActualHeightProperty;
            }
        }

- In line
sp.AddHandler(Button.Click , new RoutedEventHandler(DoSomething));
- an error occurs - swears at
Button.Click-
Error CS0120 The non-static field, method, or property 'ButtonBase.Click' requires an object reference.

But how can I pass a reference to an object if Button.Click- this is an event - except to subscribe to it on a delegate
- that is, something like this
sp.AddHandler(Button.Click+= new RoutedEventHandler(), new RoutedEventHandler(DoSomething));

But here - - it also requires a method for processing - and then a strong clutter is already obtained (I mean, I follow tutorials on the Internet and there is just a construction of the form Button.Click+= new RoutedEventHandler()
RoutedEventHandler()
sp.AddHandler(Button.Click , new RoutedEventHandler(DoSomething));
) - that is, the Click event is simply called on the Button object class and passed as the first parameter to AddHandler)
In essence, depending on the error being thrown
Error CS0120 The non-static field, method, or property 'ButtonBase.Click' requires an object reference.

- as I understand it, the compiler wants a link to the button that was pressed - i.e. then I have to paint the event
Button.Click
in some way:
sp.AddHandler(Button.Click += new RoutedEventHandler(retBTN), new RoutedEventHandler(DoSomething));
     

        private Button retBTN(object sender, RoutedEventArgs e)
        {
            return (Button)sender ;
        }
- but then the compiler swears that retBTN - has the wrong return type - apparently does not match the signature of the RoutedEventHandler delegate class. And I don't know what to do next.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
T
twobomb, 2017-07-14
@BadCats

Maybe so?

sp.AddHandler(Button.ClickEvent, new RoutedEventHandler((o,e)=>{
                Console.WriteLine("test");
            }));

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question