2

I am creating a TextBox in code-behind.

TextBox textBox = new TextBox();

I also have a function:

private void TextBox_Focus(object sender, RoutedEventArgs e)
{
    // does something
}

I want to bind TextBox_Focus to TextBox.GotFocus.

Rather than setting each property individually like so

TextBox textBox = new TextBox();
textBox.Width = 100;
textBox.Height = 25;
textBox.Background = Brushes.White;
textBox.Foreground = Brushes.Blue;
textBox.GotFocus += TextBox_Focus;

I prefer using braces (curly brackets) {}:

TextBox textBox = new TextBox()
{
   Width = 100,
   Height = 25,
   Background = Brushes.White,
   Foreground = Brushes.Blue
};

However, when I use the braces method, I am unable to bind to events.

I have tried doing the following, but to no avail...

TextBox textBox = new TextBox()
{
   Width = 100,
   Height = 25,
   Background = Brushes.White,
   Foreground = Brushes.Blue,
   this.GotFocus += TextBox_Focus
};

Question: Is there a way to event bind using the braces ({}) method?

Update: The element is being created dynamically, so I cannot use XAML.

abatishchev
  • 98,240
  • 88
  • 296
  • 433
Dom
  • 38,906
  • 12
  • 52
  • 81
  • The "braces method" is an object initializer, which should help you find [other questions that ask the same thing](http://stackoverflow.com/questions/3993601/assigning-events-in-object-initializer) – Nick Freeman Apr 10 '13 at 15:55
  • Your question starts up by saying `I am creating a TextBox in code-behind. ` - Which is generally a really bad practice unless you have a GOOD reason for that. Can you explain what you need so I can tell you the right way to implement it in WPF? – Federico Berasategui Apr 10 '13 at 15:55
  • http://stackoverflow.com/questions/3993601/assigning-events-in-object-initializer – Viv Apr 10 '13 at 15:56
  • @HighCore I wanted to simplify the example so I don't use excessive code. In my real example, I have a ListBox that users edit. When they click "Add", it creates, using code behind, an element and binds it to the list items. – Dom Apr 10 '13 at 15:58
  • 1
    You could just use bindings and XAML, unless the GotFocus event is also variable. – It'sNotALie. Apr 10 '13 at 16:03
  • 1
    The answer here has some additional info that might be interesting http://stackoverflow.com/questions/3993601/assigning-events-in-object-initializer – keyboardP Apr 10 '13 at 16:09
  • @keyboardP you are the 3rd one to post that link hah – Nick Freeman Apr 10 '13 at 16:30
  • @Dom you should use XAML for that, and not create UI elements in code ala-winforms. Even if it's "dynamic". WPF's idea of dynamic differs a lot from traditional pseudo-UI frameworks. – Federico Berasategui Apr 10 '13 at 16:46
  • 1
    @NickFreeman - *facepalm* lol. Just goes to show how good it is! :D – keyboardP Apr 10 '13 at 17:09

3 Answers3

3

No. Object initializers only work to set properties or fields. You're trying to subscribe to an event, which isn't supported in Object initializer syntax.

As other commenters are saying, XAML is the best way to initialize WPF controls.

Apparently Mono though supports what you're asking for. See: Initializing events with initializer syntax

Community
  • 1
  • 1
Shlomo
  • 14,102
  • 3
  • 28
  • 43
  • Thank you for the explanation! I'll also look into `Mono C#`. Appreciate the help! – Dom Apr 10 '13 at 16:06
1

Why not use Xaml, you'll find it is quite flexible. And also kinda WPF's thing.

<TextBox x:Name="textBox"
         Width="100"
         Height="25"
         Background="White"
         Foreground="Blue"
         GotFocus="TextBox_Focus" />

As per your comment, you can do what you wish like so:

<ListBox ItemsSource="{Binding MyCollection}">
     <ListBox.ItemTemplate>
          <DataTemplate>
                  <TextBox Text="{Binding }"
                           Width="100"
                           Height="25"
                           Background="White"
                           Foreground="Blue"
                           GotFocus="TextBox_Focus" />
          </DataTemplate>
     </ListBox.ItemTemplate>

If you make your Collection an ObservableCollection<T> when you add an item to the collection it will update your list box for you.

ywm
  • 1,107
  • 10
  • 14
  • Thanks for the response. Unfortunately, I wish I could use XAML, however, the element needs to be created dynamically. – Dom Apr 10 '13 at 16:01
  • You can still add items dynamically using XAML. Code behind isn't a magical entity. – Nick Freeman Apr 10 '13 at 16:03
  • What are you trying to generate? Is it a collection of items, because then a `DataTemplate` would be the way to go forward. – ywm Apr 10 '13 at 16:06
  • @ywm The XAML is all turned into code eventually. If it's quicker or easier in a particular context then you can use it, if it's not (even if it's possible) then don't. – Servy Apr 10 '13 at 16:10
  • 1
    Granted, but the XAML is about the same really in this case. But it fits the paradigm that others would expect when they come to maintain your WPF application. – ywm Apr 10 '13 at 16:15
-3

Try EventManager.RegisterClassHandler(typeof(TextBox),TextBox.GotKeyboardFocusEvent, new RoutedEventHandler(yourMethod());

  • 1
    How is this preferable to subscribing to the event through `object.Event += eventhandler`? Also, still couldn't be done through an object initializer, so doesn't' answer the question. – Servy Apr 10 '13 at 16:07