나는 다음과 같은 코드가 있습니다상황에 맞는 메뉴가 결합 된 항목이 표시되지 않습니다
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로 설정 됨).
누구나 왜 그런 일이 발생했는지 알 수 있습니까?
아마도 오른쪽 클릭의 기본 처리에서 WPF는 컨텍스트 메뉴에 DataContext를 할당합니다. 내 코드에서 수동으로 컨텍스트 메뉴를 열 때이 작업을 수행합니다. this.ContextMenu.DataContext = this.DataContext. 메뉴가 예상대로 작동합니다. – Jogy