Silverlight TabItem模板无法正常工作

时间:2010-04-20 10:21:25

标签: controls silverlight-4.0 controltemplate tabitem

在SL4应用程序中,我需要重新设置我的TabItems(实际上在标题中添加一个按钮)。

所以我从here获取了TabItem的控件模板,并添加了我想要的功能。

这似乎工作正常,(我可以动态添加tabitems),但有一个例外: 我认为这个发布的控件模板表现得某种程度上是“任意的”:每当鼠标悬停在一个未选择的TabItem标题上时,这将被选中,而单击!! (afaik这不是默认行为:用户用户必须单击标题才能使此tabitem成为选定的标题。)

我试图找出为什么它表现得像这样,没有运气! 是否有人可以启发我的黑暗?

提前致谢!

1 个答案:

答案 0 :(得分:0)

事实证明错误不是在控件模板中,而是在类中,应用了样式。

详细说明:应用样式的类如下(在其中您将看到我对“错误行为”的评论):

public class WorkspaceViewModel:TabItem     {

    public WorkspaceViewModel()
    {
        DefaultStyleKey = typeof(WorkspaceViewModel);
    }
    public override void OnApplyTemplate()
    {
        base.OnApplyTemplate();
        Button closeButtonSel = base.GetTemplateChild("PART_CloseTopSelected") as Button;
        Button closeButtonUnsel = base.GetTemplateChild("PART_CloseTopUnSelected") as Button;
        if (closeButtonSel != null)
            closeButtonSel.Click += new RoutedEventHandler(closeButtonSel_Click);
        if (closeButtonUnsel != null)
            closeButtonUnsel.Click += new RoutedEventHandler(closeButtonSel_Click);

        //this part is causing the effect i was complaining about!
        //and has to be removed
        this.MouseEnter += delegate(object sender, MouseEventArgs e)
        {
            IsSelected = true;
        };


    }

    void closeButtonSel_Click(object sender, RoutedEventArgs e)
    {
        //this is the close request method used in the CloseTabItemCommand
        OnRequestClose();

    }


    #region CloseTabItemCommand

    private RelayCommand closeTabItemCommand;
    public ICommand CloseTabItemCommand
    {
        get
        {
            if (this.closeTabItemCommand == null)
                this.closeTabItemCommand = new RelayCommand(p => this.OnRequestClose(), p => this.CanCloseTabItem());

            return this.closeTabItemCommand;
        }
    }
    private bool CanCloseTabItem()
    {
        return true;
    }

    public event EventHandler RequestClose;
    private void OnRequestClose()
    {
        if (RequestClose != null)
            RequestClose(this, EventArgs.Empty);
    }
    #endregion
}