WPF 2d阵列绑定和上下文菜单
本文关键字:上下文 菜单 绑定 2d 阵列 WPF | 更新日期: 2023-09-27 18:17:06
我在WPF中有一个命令绑定问题。我尝试用ItemsControls显示2D-array,我有以下代码:
xaml:<ItemsControl x:Name="Lst" ItemsSource="{Binding Items}" ItemTemplate="{DynamicResource DataTemplateLevel1}"/>
<DataTemplate x:Key="DataTemplateLevel1">
<ItemsControl ItemsSource="{Binding}" ItemTemplate="{DynamicResource FirstTemplate}">
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<StackPanel Orientation="Horizontal"/>
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
</ItemsControl>
</DataTemplate>
<DataTemplate x:Key="FirstTemplate" >
<Border BorderThickness="1" BorderBrush="Black" Margin="3, 3, 3, 3"
Tag="{Binding DataContext, ElementName=Lst}">
<Border.ContextMenu>
<ContextMenu DataContext="{Binding PlacementTarget.Tag, RelativeSource={RelativeSource Self}}" Tag="{Binding Items}" >
<MenuItem Header="Delete" Command="{Binding SomeCommand}"
CommandParameter="What should i write here?" />
</ContextMenu>
</Border.ContextMenu>
<Grid Background="MediumSeaGreen" >
<Grid.RowDefinitions>
<RowDefinition />
<RowDefinition />
</Grid.RowDefinitions>
<Label Grid.Row="0" Grid.Column="0" Name="IdLabel" Content="{Binding Id}" />
<Label Grid.Row="1" Grid.Column="0" HorizontalAlignment="Left"
Foreground="White" Margin="5, 0, 0, 0"
FontSize="20" FontWeight="Heavy" Content="{Binding Name}" />
</Grid>
</Border>
</DataTemplate>
我有ViewModel:
public class ViewModel
{
public List<List<Model>> Items
{
get
{
var lsts = new List<List<Model>>();
for (int i = 0; i < 5; i++)
{
var range = new List<Model>();
for (int j = 0; j < 5; j++)
range.Add(new Model{ Id = i*5 + j, Name = "Some item" });
lsts.Add(range);
}
return lsts;
}
}
private readonly ICommand _command = new MyCommand();
public ICommand SomeCommand { get { return _command; } }
}
当我点击ContextMenu的项目命令SomeCommand正在发射。但是我不能传递这个命令参数。ContextMenu的DataContext被绑定到Border。标签绑定到名为Lst的元素的DataContext,现在我不能将命令参数绑定到名为IdLabel的标签的内容。
概要:
我想将MenuItem的命令绑定到ItemsControl的数据文本(元素Lst),我想将命令参数绑定到这个ItemsControl的项目的数据文本(到IdLabel的内容)
我怎么能这么做呢?提前感谢!
根据你的模板和数据模型,这应该可以工作
<ContextMenu DataContext="{Binding PlacementTarget, RelativeSource={RelativeSource Self}}" Tag="{Binding Tag.Items}" >
<MenuItem Header="Delete" Command="{Binding Tag.SomeCommand}"
CommandParameter="{Binding DataContext}" />
</ContextMenu>
假设PlacementTarget(Border)
是您试图将其DataContext(Model)
传递给命令的元素
如果你想传递模型的Id
属性,只需重写为
<ContextMenu DataContext="{Binding PlacementTarget, RelativeSource={RelativeSource Self}}" Tag="{Binding Tag.Items}" >
<MenuItem Header="Delete" Command="{Binding Tag.SomeCommand}"
CommandParameter="{Binding DataContext.Id}" />
</ContextMenu>