views:

261

answers:

1

Hi there!

Sit Rep I have a WPF app. In the constructor of the (C#) code-behind I attach a button event-handler. Problem is, it doesn't attach! But if I attach it via clicking a UI button, then the button works fine. Also, of course, if I attach it in the button's XAML it works too.

So, it appears that the prob is attaching the handler in the constructor. It seems to be too early in the process.

App Image

This is what I want, but doesn't attach:

public MainWindow()
{
   InitializeComponent();

   //...
   //
   //  TEST RADIO BUTTONS
   //
   //  THIS HANDLER DOESN'T ATTACH!
   ui_Test.Click += (object sender, RoutedEventArgs e) =>
   {
       bool localOnly = Convert.ToBoolean(ui_rdoLocal.IsChecked);
       bool onlineOnly = Convert.ToBoolean(ui_rdoOnline.IsChecked);
       bool both = Convert.ToBoolean(ui_rdoBoth.IsChecked);

       string message = "Local: {1}{0}Online: {2}{0}Both: {3}".Put(nl, localOnly, onlineOnly, both);
       MessageBox.Show(message);
    };

   //...
}

And here's the code for a second test button which attaches the above code via a button click. This handler is set in XAML. The handler then works, but I want to attach the handler in C#, not XAML.

<Button Name="ui_Test2" Content="Attach Annonymous Handlers" Margin="30,10" Click="ui_Test2_Click"></Button>

And the method:

    /// <summary>
    /// Attaches control handlers. Will they attach now? YES!!
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    private void ui_Test2_Click(object sender, RoutedEventArgs e)
    {
        ui_Test.Click += (object sndr, RoutedEventArgs rea) =>
            {
                bool localOnly = Convert.ToBoolean(ui_rdoLocal.IsChecked);
                bool onlineOnly = Convert.ToBoolean(ui_rdoOnline.IsChecked);
                bool both = Convert.ToBoolean(ui_rdoBoth.IsChecked);

                string message = "Local: {1}{0}Online: {2}{0}Both: {3}".Put(nl, localOnly, onlineOnly, both);
                MessageBox.Show(message);
            };
    }

Thx in advance for any help!

Gregg

A: 

Try to attach handler after calling InitializeComponent(); in constructor.

inTagger
Thanks. Actually it is after that call. I'll add it above to clarify for others though.
Gregg Cleland