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.