使用{}进行事件绑定

本文关键字:事件 绑定 使用 | 更新日期: 2023-09-27 18:08:42

我正在创建一个代码隐藏的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。

使用{}进行事件绑定

No。对象初始化器只用于设置属性或字段。您正在尝试订阅一个事件,对象初始化器语法不支持。

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

显然Mono虽然支持你所要求的。参见:使用初始化器语法初始化事件

为什么不使用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>,当你向集合中添加一个项目时,它会为你更新你的列表框。

尝试一下EventManager.RegisterClassHandler (typeof(文本框),文本框。GotKeyboardFocusEvent, new RoutedEventHandler(yourMethod());