[英]Binding an observable collection to a context menu
I am trying to make a context menu show up a list of strings. 我正在尝试使上下文菜单显示字符串列表。 The app contains a datagrid of people who can be Edited,Deleted and Added to a group.
该应用程序包含可以编辑,删除和添加到组的人员的数据网格。 I have a class StudentGroup which are different groups a person can be added (One of the Members of StudentGroup is Name).
我有一个类StudentGroup,可以添加一个人不同的组(StudentGroup的一个成员是Name)。 ViewModel retrieves the full list of groups and puts it inside an Observable Collection.
ViewModel检索完整的组列表并将其放入Observable Collection中。 I am trying to make the context menu work such that whenever a user right clicks and hover over Add User to -> it opens a side menuitems that contains the Observable Collections's Name string.
我正在尝试使上下文菜单工作,以便每当用户右键单击并将鼠标悬停在添加用户上时 - >它会打开包含Observable Collections的Name字符串的侧面菜单项。
This is what I have tried so far by looking up similar questions on StackOverflow, but it hasn't worked for me yet. 这是我到目前为止通过在StackOverflow上查找类似问题而尝试过的,但它对我来说还没有用。
The XAML: XAML:
<DataGrid.ContextMenu>
<ContextMenu AllowDrop="True" ItemsSource="{Binding Entries}">
<MenuItem Header="Edit" />
<MenuItem Header="Delete"/>
<MenuItem Header="Add User to">
<MenuItem.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding Name}" />
</DataTemplate>
</MenuItem.ItemTemplate>
</MenuItem>
</ContextMenu>
</DataGrid.ContextMenu>
XAML Code behind View: 查看后面的XAML代码:
private TitleViewMode TVM=new TitleViewMode;
public Welcome()
{
InitializeComponent();
_grid1.ContextMenu.DataContext = TVM;
}
ViewModel 视图模型
class TitleViewModel
{
public ObservableCollection<StudentGroup> Entries {get;set;}
private List<StudentGroup> sg1 { get; set;}
public TitletViewModel()
{
sg1 = GetGroups();
Entries = new ObservableCollection<StudentGroup>(sg1);
}
}
This should work 这应该工作
<MenuItem Header="Add User to" ItemsSource="{Binding Entries}">
<MenuItem.ItemTemplate>
<DataTemplate>
<MenuItem Header="{Binding Name}"></MenuItem>
</DataTemplate>
</MenuItem.ItemTemplate>
</MenuItem>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.