显式打开时,上下文菜单不显示绑定项(通过ContextMenu.IsOpen)

时间:2011-03-08 10:53:07

标签: c# .net wpf

我有以下代码:

XAML:

<Window x:Class="ContextMenuIssue.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="350" Width="525">
    <Grid>
      <TextBox MouseRightButtonUp="TextBox_OnMouseRightButtonUp">
        <TextBox.ContextMenu>
          <ContextMenu ItemsSource="{Binding Items}"></ContextMenu>
        </TextBox.ContextMenu>
      </TextBox>
    </Grid>
</Window>

代码背后:

namespace ContextMenuIssue
{
    class Model
    {
        public Model()
        {
            _items = new List<string> {"A", "B", "C"};
        }

        private List<string> _items;
        public List<string> Items
        {
            get { return _items; }
            set { _items = value; }
        }
    }

    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
            this.DataContext = new Model();
        }

        private void TextBox_OnMouseRightButtonUp(object sender, MouseButtonEventArgs e)
        {
            //TextBox textBox = ((TextBox) sender);

            //textBox.ContextMenu.IsOpen = true;
            //e.Handled = true;
        }
    }
}

当我运行它并右键单击文本框时,我得到了一个上下文菜单,正如预期的3个项目(A,B和C)。但是,如果我尝试显式打开上下文菜单,通过在TextBox_OnMouseRightButtonUp中注释掉代码,我会得到一个空的上下文菜单。

当我尝试调试它时,似乎上下文菜单对象存在,但它是空的且未初始化,例如,其ItemsSource属性设置为null。

任何人都知道为什么会这样?

1 个答案:

答案 0 :(得分:3)

ContextMenu不属于元素树,因此,DataContext属性无法传播到ContextMenu。要解决此问题,请在OnMouseRightButtonUp中手动设置ContextMenu的数据上下文:

textBox.ContextMenu.DataContext = this.DataContext;