c# - 使用 { } 的事件绑定(bind)

标签 c# wpf events binding

<分区>

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

最佳答案

没有。 Object initializers仅用于设置属性或字段。您正在尝试订阅对象初始化程序语法不支持的事件。

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

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

关于c# - 使用 { } 的事件绑定(bind),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15930640/

相关文章:

c# - C# 中的 eBay API GetSellerList 调用返回错误 14005 'Web Service framework internal error. execute exception.'

wpf - 在什么情况下 ICommand CanExecute 可能不会更新?

c# - Telerik GridView 粘贴

c# - 在 WPF 中使用 HSV 而不是 RGB

php - PHP 中的事件监听器

c# - 为什么我的 C# AppDomain 前一秒还好,下一秒就抛出异常?

c# - ASP.NET GridView : How to edit and delete data records

c# - 在 .NET 4 下运行的 .NET 2 和 .NET 4 程序集之间有什么区别

javascript - 动态创建的元素上的事件绑定(bind)?

javascript - $(this.element) 未定义,不明白为什么