使用{}进行事件绑定

时间:2013-04-10 15:52:12

标签: c# wpf events binding

我在代码隐藏中创建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。

3 个答案:

答案 0 :(得分:3)

没有。 Object initializers仅用于设置属性或字段。您正在尝试订阅一个事件,这在Object initializer语法中不受支持。

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

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

答案 1 :(得分: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>,则会为您更新列表框。

答案 2 :(得分:-3)

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