我在代码隐藏中创建了一个TextBox
。使用{}绑定事件
TextBox textBox = new TextBox();
我也有一个功能:
private void TextBox_Focus(object sender, RoutedEventArgs e)
{
// does something
}
我要绑定TextBox_Focus
到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
};
然而,当我使用括号方法,我不能结合到事件。
我曾尝试做以下,但无济于事...
TextBox textBox = new TextBox()
{
Width = 100,
Height = 25,
Background = Brushes.White,
Foreground = Brushes.Blue,
this.GotFocus += TextBox_Focus
};
问: 有没有办法使用括号({}
)方法绑定事件?
更新: 该元素是动态创建的,所以我不能使用XAML。
的 “括号法” 是一个对象初始化,这将有助于你找到[其他问题相同的东西](http://stackoverflow.com/questions/3993601/assigning-events-in-object-initializer) – 2013-04-10 15:55:31
你的问题开始说'我在代码隐藏中创建一个文本框。' - 这通常是一个非常糟糕的做法,除非你有一个很好的理由,你能解释一下你需要什么,所以我可以告诉你在WPF中实现它的正确方法吗? – 2013-04-10 15:55:46
http://stackoverflow.com/questions/3993601/assigning -events-in-object-initializer – Viv 2013-04-10 15:56:50