2017-11-09 10 views
0

.NET 4.6에서 Prism을 사용하는 WPF 응용 프로그램에는 ListBox가있는 User 컨트롤이 있습니다. 컨텍스트 메뉴를 목록 상자의 항목에 연결하고 클릭하면보기 모델에서 명령을 실행하려고합니다.ListBox의 컨텍스트 메뉴 명령이 실행되지 않습니다.

상황에 맞는 메뉴가 올바르게 표시됩니다. 그러나 메뉴를 클릭해도 아무 것도 보이지 않습니다.

여기 내 Xaml (관련없는 모든 코드 제거)입니다. 내보기 모델 (다시 여기

<ContextMenu> 
<MenuItem Header="Move to User Group" Command="{Binding AddGroupToUserGroupsCommand}" 
             CommandParameter="{Binding}"/> 

과 :

<UserControl xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
       xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
       xmlns:prism="http://prismlibrary.com/" xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity" 
       xmlns:ei="http://schemas.microsoft.com/expression/2010/interactions" 
       xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
       xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
       xmlns:syncfusion="http://schemas.syncfusion.com/wpf" 
       x:Class="DynaProPOS.WPF.Views.UserAuthorization" 
       prism:ViewModelLocator.AutoWireViewModel="True" 
       mc:Ignorable="d" d:DesignHeight="600" d:DesignWidth="1000"> 
    <Grid> 
     <ListBox Margin="15,5" x:Name="lbxGroups" Grid.Row="2" Grid.Column="2" Grid.RowSpan="1" 
        ItemsSource="{ Binding Groups }" SelectionMode="Single" SelectedValuePath="IdKey" 
        DisplayMemberPath="GroupName" SelectedItem="{Binding SelectedGroup, Mode=TwoWay}"> 
      <ListBox.ItemContainerStyle> 
       <Style TargetType="ListBoxItem"> 
        <Setter Property="ContextMenu"> 
         <Setter.Value> 
     <ContextMenu> 
      <MenuItem Header="Move to User Group" Command="{Binding AddGroupToUserGroupsCommand}"/> 
     </ContextMenu> 

         </Setter.Value> 
        </Setter> 
       </Style> 
      </ListBox.ItemContainerStyle> 
     </ListBox> 
    </Grid> 
</UserControl> 

은 또한 다음 (에 StackOverflow에 대한 발견이 샘플)

     <ContextMenu DataContext="{Binding PlacementTarget.Tag, RelativeSource={RelativeSource Self}}"> 
          <MenuItem Header="Move to User Group" Command="{Binding AddGroupToUserGroupsCommand}" 
             CommandParameter="{Binding}"/> 
         </ContextMenu> 

이 중 하나를 시도 , 모든 관련없는 코드가 삭제됨).

public class UserAuthorizationViewModel : BindableBase 
{ 
    private IAuthenticationService authService; 
    private User selectedUser; 
    private Users2Groups selectedUserGroup; 
    private Group selectedGroup; 
    private ObservableCollection<User> users; 
    private ObservableCollection<Users2Groups> users2Groups; 
    private ObservableCollection<Group> groups; 
    private ObservableCollection<Group> selectedGroups; 
    private ObservableCollection<Users2Groups> selectedUserGroups; 
    private ObservableCollection<Groups2Permissions> groupPermissions; 
    private ObservableCollection<Permission> allPermissions; 
    private IRegionManager regionMgr; 
    private ObservableCollection<Permission> selectedPermissions; 

    public DelegateCommand AddGroupToUserGroupsCommand { get; private set; } 

    public UserAuthorizationViewModel(IAuthenticationService _authService, IRegionManager _regionMgr) 
    { 
     authService = _authService; 
     regionMgr = _regionMgr; 
     AddGroupToUserGroupsCommand = new DelegateCommand(async() => await AddGroupToUserGroups()); 
    } 

    private async Task AddGroupToUserGroups() 
    { 
     if (SelectedUser == null) 
      return; 

     foreach (var sg in SelectedGroups) 
     { 
      if (!UserGroups.Any(x => x.Group.IdKey == sg.IdKey)) 
      { 
       var newUg = new Users2Groups(); 
       newUg.User = SelectedUser; 
       newUg.Group = sg; 
       newUg.ObjectStateEnum = ObjectStateEnum.Added; 
       await Task.Run(() => UserGroups.Add(newUg)); 
      } 
     } 

    } 
} 

명령 처리기의 중단 점에 절대로 도달하지 않습니다. 누군가 제발 나를 도와 줄 수 있니?

수정 확인. 컨텍스트 메뉴에서 첨부 된 명령을 실행하는 방법을 찾았습니다. 그러나 이제 문제는 어디에서나 마우스 오른쪽 버튼을 클릭하여 컨텍스트 메뉴가 나타나는 것입니다. 내가 필요로 무엇

<UserControl xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
      xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
      xmlns:prism="http://prismlibrary.com/" xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity" 
      xmlns:ei="http://schemas.microsoft.com/expression/2010/interactions" 
      xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
      xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
      xmlns:syncfusion="http://schemas.syncfusion.com/wpf" 
      x:Class="DynaProPOS.WPF.Views.UserAuthorization" 
      prism:ViewModelLocator.AutoWireViewModel="True" 
      mc:Ignorable="d" d:DesignHeight="600" d:DesignWidth="1000"> 
<Grid> 
    <ListBox x:Name="lbxPermissions" HorizontalAlignment="Stretch" Grid.Row="2" 
        Grid.Column="3" Grid.RowSpan="3" Margin="15,10" VerticalAlignment="Stretch" 
        ItemsSource="{Binding AllPermissions}" SelectedValuePath="IdKey" 
        ScrollViewer.VerticalScrollBarVisibility="Auto"> 
     <ListBox.ItemTemplate> 
      <DataTemplate> 
       <TextBlock Text="{Binding PermissionName}"/> 
      </DataTemplate> 
     </ListBox.ItemTemplate> 
     <ListBox.ContextMenu> 
      <ContextMenu> 
       <MenuItem Header="Add to Group" Command="{Binding AddPermissionToGroupsCommand}"/> 
      </ContextMenu> 
     </ListBox.ContextMenu> 
    </ListBox> 
</Grid> 

내가 바로 목록 상자의 항목을 클릭하는 경우에만 나타나는 상황에 맞는 메뉴를 제한하는 것입니다. 그래서, 내가 사용한이 샘플 코드를 찾았습니다. 이렇게하면 컨텍스트 메뉴가 ListBox 항목에만 나타납니다. 그러나 문맥 메뉴 항목을 클릭하면 내 명령이 실행되지 않는 문제가 있습니다.

 <ListBox x:Name="lbxPermissions" HorizontalAlignment="Stretch" Grid.Row="2" 
        Grid.Column="3" Grid.RowSpan="3" Margin="15,10" VerticalAlignment="Stretch" 
        ItemsSource="{Binding AllPermissions}" SelectedValuePath="IdKey" 
        ScrollViewer.VerticalScrollBarVisibility="Auto"> 
     <ListBox.ItemTemplate> 
      <DataTemplate> 
       <TextBlock Text="{Binding PermissionName}"/> 
      </DataTemplate> 
     </ListBox.ItemTemplate> 
     <ListBox.ItemContainerStyle> 
      <Style TargetType="ListBoxItem"> 
       <Setter Property="ContextMenu"> 
        <Setter.Value> 
         <ContextMenu> 
          <MenuItem Header="Add to Group" Command="{Binding AddPermissionToGroupsCommand}"/> 
         </ContextMenu> 
        </Setter.Value> 
       </Setter> 
      </Style> 
     </ListBox.ItemContainerStyle> 
    </ListBox> 

도움이 필요하십니까? 누군가? 부디?

답변

1

귀속 뷰 모델에 ListBoxItemTag 재산권 및 ContextMenuPlacementTarget 속성 사용하여 명령 바인딩 :

<ListBox Margin="15,5" x:Name="lbxGroups" Grid.Row="2" Grid.Column="2" Grid.RowSpan="1" 
     ItemsSource="{Binding Groups}" SelectionMode="Single" SelectedValuePath="IdKey" 
     DisplayMemberPath="GroupName" SelectedItem="{Binding SelectedGroup, Mode=TwoWay}"> 
    <ListBox.ItemContainerStyle> 
     <Style TargetType="ListBoxItem"> 
      <Setter Property="Tag" Value="{Binding Path=DataContext, RelativeSource={RelativeSource AncestorType=ListBox}}" /> 
      <Setter Property="ContextMenu"> 
       <Setter.Value> 
        <ContextMenu> 
         <MenuItem Header="Move to User Group" 
            Command="{Binding PlacementTarget.Tag.AddGroupToUserGroupsCommand, RelativeSource={RelativeSource AncestorType=ContextMenu}}"/> 
        </ContextMenu> 
       </Setter.Value> 
      </Setter> 
     </Style> 
    </ListBox.ItemContainerStyle> 
</ListBox> 

이 작동한다 AddGroupToUserGroupsCommand 재산권 동일한 속하는 것으로 가정하면 모델 클래스를 Groups 속성으로 사용하십시오.

+0

Tag 속성을 설정하는 코드 줄을 완전히 놓쳤습니다. 나는 그것없이 노력하고 있었고 분명히 효과가 없었습니다. 나는 단지 그것을 알아 차렸다. 그리고 그것은 지금 완벽하게 작동한다. 감사합니다 @ mm8. 나는 이것을 대답으로 받아들입니다. –

0

ListBox 태그 속성에 바인딩이 필요합니다. 명령 바인딩을 위해 PlacementTarget.Tag를 수행하려고하기 때문에.

<ListBox Margin="15,5" x:Name="lbxGroups" Grid.Row="2" 
Tag={Binding} Grid.Column="2" Grid.RowSpan="1" 
       ItemsSource="{ Binding Groups }" SelectionMode="Single" SelectedValuePath="IdKey" 
       DisplayMemberPath="GroupName" SelectedItem="{Binding SelectedGroup, Mode=TwoWay}"> 
     <ListBox.ItemContainerStyle> 
      <Style TargetType="ListBoxItem"> 
       <Setter Property="ContextMenu"> 
        <Setter.Value> 
         <ContextMenu DataContext="{Binding PlacementTarget.Tag, RelativeSource={RelativeSource Self}}"> 
          <MenuItem Header="Move to User Group" Command="{Binding AddGroupToUserGroupsCommand}" 
             CommandParameter="{Binding}"/> 
         </ContextMenu> 
        </Setter.Value> 
       </Setter> 
      </Style> 
     </ListBox.ItemContainerStyle> 
    </ListBox> 
+0

내가 보여주는 컨텍스트 메뉴 코드는 내가 찾은 다른 컨텍스트 메뉴 관련 코드에서 나왔습니다. PlacementTarget.Tag 바인딩이 의미하거나 실제로 무엇인지 이해하지 못합니다. 나는 그들 중 어떤 것이 작동하는지보기 위해 다른 속성을 시도했다. 그들은하지 않습니다. 작동 방식을 아는 경우 코드를 붙여 넣을 수 있습니까? 붙여 넣은 코드에 새로운 것이 보이지 않습니다. –