<分区>
我正在代码隐藏中创建一个 TextBox
。
TextBox textBox = new TextBox();
我还有一个功能:
private void TextBox_Focus(object sender, RoutedEventArgs e)
{
// does something
}
我想将 TextBox_Focus
绑定(bind)到 TextBox.GotFocus
。
而不是像这样单独设置每个属性
TextBox textBox = new TextBox();
textBox.Width = 100;
textBox.Height = 25;
textBox.Background = Brushes.White;
textBox.Foreground = Brushes.Blue;
textBox.GotFocus += TextBox_Focus;
我更喜欢使用大括号(花括号){}
:
TextBox textBox = new TextBox()
{
Width = 100,
Height = 25,
Background = Brushes.White,
Foreground = Brushes.Blue
};
但是,当我使用大括号方法时,我无法绑定(bind)到事件。
我尝试了以下操作,但无济于事......
TextBox textBox = new TextBox()
{
Width = 100,
Height = 25,
Background = Brushes.White,
Foreground = Brushes.Blue,
this.GotFocus += TextBox_Focus
};
问题:
有没有一种方法可以使用大括号 ({}
) 方法进行事件绑定(bind)?
更新: 该元素是动态创建的,因此我无法使用 XAML。