【发布时间】:2015-02-03 07:22:15
【问题描述】:
可能我还没有真正理解 WPF 中的事件系统。
我有一个 TabItem,它的标题由一个 TextBox 和一个 Button 组成。 TextBox 是只读的。 (在真实的应用程序中,它允许双击编辑,但这无关紧要。)
选择选项卡很困难,因为 TextBox 会抓取 MouseLeftButtonDown 事件。因此,我向 TabItem 添加了一个事件处理程序,将其置于前台。但是,使用该事件处理程序,按钮不再接收事件。为什么在 TabItem 得到事件之前按钮没有得到事件?我认为它从叶子到逻辑树的根部冒泡。
这是 XAML:
<Window x:Class="tt_WPF.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:tt_WPF"
Title="MainWindow" SizeToContent="WidthAndHeight">
<TabControl x:Name="TC"></TabControl>
</Window>
下面是代码:
public class myItem : TabItem
{
public myItem(string name)
{
// Create horizontal StackPanel
StackPanel sp = new StackPanel();
sp.Orientation = Orientation.Horizontal;
// Create a readonly TextBox
TextBox tb = new TextBox();
tb.Text = name;
tb.IsReadOnly = true;
// Create a Button with a simple command
Button b = new Button();
b.Content = "X";
b.Click += Button_Click;
// Add Button and TextBlock to StackPanel and StackPanel to this TabIten
sp.Children.Add(tb);
sp.Children.Add(b);
this.Header = sp;
this.Content = "This is " + name;
// --> Here's the trouble: Install an event handler that brings the TabItem into foreground when clicked
this.AddHandler(MouseLeftButtonDownEvent, new RoutedEventHandler(TabItem_MouseLeftButtonDownEvent), true);
}
private void Button_Click(object sender, RoutedEventArgs e)
{
MessageBox.Show("Button X");
}
private void TabItem_MouseLeftButtonDownEvent(object sender, RoutedEventArgs e)
{
this.IsSelected = true;
}
}
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
TC.Items.Add(new myItem("Tab 1"));
TC.Items.Add(new myItem("Tab 2"));
}
}
【问题讨论】: