2013-04-10 53 views
2

我在代码隐藏中创建了一个TextBox使用{}绑定事件

TextBox textBox = new TextBox(); 

我也有一个功能:

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

我要绑定TextBox_FocusTextBox.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。

+0

的 “括号法” 是一个对象初始化,这将有助于你找到[其他问题相同的东西](http://stackoverflow.com/questions/3993601/assigning-events-in-object-initializer) – 2013-04-10 15:55:31

+0

你的问题开始说'我在代码隐藏中创建一个文本框。' - 这通常是一个非常糟糕的做法,除非你有一个很好的理由,你能解释一下你需要什么,所以我可以告诉你在WPF中实现它的正确方法吗? – 2013-04-10 15:55:46

+0

http://stackoverflow.com/questions/3993601/assigning -events-in-object-initializer – Viv 2013-04-10 15:56:50

回答

3

编号Object initializers只能设置属性或字段。您正尝试订阅一个事件,该事件在Object initializer语法中不受支持。

正如其他评论者所说,XAML是初始化WPF控件的最佳方式。

显然单声道虽然支持你所要求的。请参阅:Initializing events with initializer syntax

+0

谢谢你的解释!我也会研究'Mono C#'。感谢帮助! – Dom 2013-04-10 16:06:23

1

为什么不使用Xaml,你会发现它非常灵活。 还有点WPF的东西。

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

根据你的评论,你可以做你希望的东西,像这样:

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

如果你让你收藏的ObservableCollection<T>当你添加一个项目到集合,它会更新列表框您。

+0

感谢您的回应。不幸的是,我希望我可以使用XAML,但是,元素需要动态创建。 – Dom 2013-04-10 16:01:23

+0

您仍然可以使用XAML动态添加项目。后面的代码不是一个神奇的实体。 – 2013-04-10 16:03:03

+0

你想要生成什么?它是一个项目的集合,因为那么'DataTemplate'就是前进的道路。 – ywm 2013-04-10 16:06:02

-3

尝试 EventManager.RegisterClassHandler(typeof运算(文本框),TextBox.GotKeyboardFocusEvent,新RoutedEventHandler(yourMethod());

+1

如何通过'object.Event + = eventhandler'来订阅事件?而且,仍然不能通过对象初始化器来完成,所以不能'回答这个问题。 – Servy 2013-04-10 16:07:46