목록의 항목에는 상황에 맞는 메뉴가 있습니다. 컨텍스트 메뉴 항목은 라우트 된 명령에 바인드됩니다.WPF - ContextMenu 항목이 ListBox에는 작동하지만 ItemsControl에는 작동하지 않는 이유는 무엇입니까?
목록 컨트롤이 ListBox
일 경우 상황에 맞는 메뉴 항목이 올바르게 작동하지만 나중에 ItemsControl
으로 다운 그레이드하면 더 이상 작동하지 않습니다. 특히 메뉴 항목은 항상 회색으로 표시됩니다. 내 CommandBinding
에 CanExecute
콜백이 호출되지 않습니다.
명령이 포함 된 상황에 맞는 메뉴 항목을 올바르게 바인딩 할 수있는 약 ListBox
은 무엇입니까? 뷰 모델과 데이터 항목에 대한 C# 코드 여기
<!-- Data template for items -->
<DataTemplate DataType="{x:Type local:Widget}">
<StackPanel Orientation="Horizontal">
<StackPanel.ContextMenu>
<ContextMenu>
<MenuItem Header="UseWidget"
Command="{x:Static l:WidgetListControl.UseWidgetCommand}"
CommandParameter="{Binding}" />
</ContextMenu>
</StackPanel.ContextMenu>
<TextBlock Text="{Binding Path=Name}" />
<TextBlock Text="{Binding Path=Price}" />
</StackPanel>
</DataTemplate>
<!-- Binding -->
<UserControl.CommandBindings>
<CommandBinding Command="{x:Static l:WidgetListControl.UseWidgetCommand}"
Executed="OnUseWidgetExecuted"
CanExecute="CanUseWidgetExecute" />
</UserControl.CommandBindings>
<!-- ItemsControl doesn't work... -->
<ItemsControl ItemsSource="{Binding Path=Widgets}" />
<!-- But change it to ListBox, and it works! -->
<ListBox ItemsSource="{Binding Path=Widgets}" />
것 : 여기
public sealed class WidgetListViewModel
{
public ObservableCollection<Widget> Widgets { get; private set; }
public WidgetViewModel()
{
Widgets = new ObservableCollection<Widget>
{
new Widget { Name = "Flopple", Price = 1.234 },
new Widget { Name = "Fudge", Price = 4.321 }
};
}
}
public sealed class Widget
{
public string Name { get; set; }
public double Price { get; set; }
}
는 C# 코드의 다음
내가 문제를 강조하기 위해 함께 넣어 샘플 응용 프로그램에서 일부 발췌 - 제어 할 수있는 것 :
public partial class WidgetListControl
{
public static readonly ICommand UseWidgetCommand
= new RoutedCommand("UseWidget", typeof(WidgetListWindow));
public WidgetListControl()
{
InitializeComponent();
}
private void OnUseWidgetExecuted(object s, ExecutedRoutedEventArgs e)
{
var widget = (Widget)e.Parameter;
MessageBox.Show("Widget used: " + widget.Name);
}
private void CanUseWidgetExecute(object s, CanExecuteRoutedEventArgs e)
{
e.CanExecute = true;
e.Handled = true;
}
}
질문을 반복하면됩니다. ListBox
은 컨텍스트 메뉴 항목 명령을 올바르게 바인딩 할 수있게 해주고, ItemsControl
에 대해이 작업을 수행 할 수있는 방법이 있습니까?
ItemsControl을 사용할 때 ContextMenu에서 직접 CommandBindings를 정의하면 작동하지만이 명령은 처음부터 명령을 사용하는 목적을 상실합니다. 내 생각 엔이 ListBoxItem 개체의 항목을 래핑하는 ListBox 함께 할 수있는 뭔가가있다 ... –