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。

4

3 回答 3

3

No. Object initializers only work to set properties or fields. You're trying to subscribe to an event, which isn't supported in Object initializer syntax.

As other commenters are saying, XAML is the best way to initialize WPF controls.

Apparently Mono though supports what you're asking for. See: Initializing events with initializer syntax

于 2013-04-10T16:01:51.637 回答
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>

If you make your Collection an ObservableCollection<T> when you add an item to the collection it will update your list box for you.

于 2013-04-10T15:58:00.203 回答
-3

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

于 2013-04-10T16:07:08.213 回答