所以我有一个上下文菜单为每个单独的listview项目和listview绑定到一个用户列表。上下文菜单有一个子菜单,该子菜单绑定到一个可观察的用户状态集合。我希望能够从列表视图传递用户id和从上下文菜单到我的更新命令参数的新状态id。我刚刚研究了多重绑定,并相信这可能是一个很好的长期解决方案,我可以在其他地方使用。下面是一些代码:
ListView from User View:
<ListView Background="Transparent" ItemsSource="{Binding UserList}" SelectionMode="Single">
<ListView.Resources>
<ContextMenu x:Key="Menu" DataContext="{Binding Path=PlacementTarget.DataContext, RelativeSource={RelativeSource Self}}">
<MenuItem Name="UserID" Header="{Binding UserID}"/>
<Separator></Separator>
<MenuItem Header="Status" ItemsSource="{Binding DataContext.UserStatus, RelativeSource={RelativeSource FindAncestor, AncestorType=UserControl}}"
DisplayMemberPath="Name" Name="StatusID">
<MenuItem.ItemContainerStyle>
<Style TargetType="MenuItem">
<Setter Property="Command" Value="{Binding DataContext.UpdateDriverStatus, RelativeSource={RelativeSource FindAncestor, AncestorType=UserControl}}" />
<Setter Property="CommandParameter" Value="{Binding}" />
</Style>
</MenuItem.ItemContainerStyle>
<MenuItem.CommandParameter>
<MultiBinding Converter="{StaticResource MultiBindConverter}">
<Binding ElementName="DriverID"></Binding>
<Binding ElementName="StatusID"></Binding>
</MultiBinding>
</MenuItem.CommandParameter> </MenuItem>
</ContextMenu>
</ListView.Resources>
<ListView.ItemContainerStyle>
<Style TargetType="{x:Type ListViewItem}">
<Setter Property="ContextMenu" Value="{StaticResource Menu}" />
</Style>
</ListView.ItemContainerStyle>
<ListView.ItemTemplate>
<ItemContainerTemplate>
<TextBlock Text="{Binding UserName}" >
</TextBlock>
</ItemContainerTemplate>
</ListView.ItemTemplate>
</ListView>
用户虚拟机:
public class UsersPanelVM : ViewModelBase, INotifyPropertyChanged
{
public ObservableCollection<UserPanelItem> UserList { get; set; }
public ObservableCollection<UserStatusList> UserStatus { get; set; }
private readonly IUserService _userService;
public IUserService UserService { get { return this._userService; } }
public UsersPanelVM(IUserService userService)
{
this._userService = userService;
var model = this.UserService.GetUsers();
this.UserList = model.Users;
var statusmodel = this.UserService.GetUserStatus();
this.UserStatus = statusmodel.UserStatus;
this.UpdateUserStatus = new RelayCommand<UserStatusList>((s) => UpdateStatus(1,s));
}
//The 1, above, is hard coded to test the method call, but ideally that should be the selected UserID
private void UpdateStatus(int ID, UserStatusList s)
{
}
public RelayCommand<UserStatusList> UpdateUserStatus { get; private set; }
}
-
这是没有必要的,因为我已经在你的其他问题中提到过,因为你有所有的信息,除了新的状态在你的对象模型。
将命令和
UpdateStatus
方法移动到UserPanelItem
的类中,该类也应该包含您的ID,然后您只需将命令更改为:new RelayCommand(param => UpdateStatus(ID, (UserStatusList)param))
-
如果你真的想这样做:你再次设置父
MenuItem
的CommandParameter
,其命令永远不会被使用,将其移动到CommandParameter
-Setter
的Value
的容器样式,即<Setter Property="CommandParameter"> <Setter.Value> <MultiBinding ...> ....