【发布时间】:2014-08-08 21:54:06
【问题描述】:
我在 WPF 中遇到 commandS-BINDING 的问题。我尝试使用 ItemsControls 显示二维数组,我有以下代码:
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.Tag 绑定到名为 Lst 的元素的 DataContext,现在我无法将命令参数绑定到名为 IdLabel 的标签的内容。
总结:
我想将 MenuItem 的命令绑定到 ItemsControl 的 DataContext(元素 Lst),并且我想将命令参数绑定到此 itemsControl 的项的 DataContext(到 IdLabel 的内容)
我该怎么做?预先感谢!
【问题讨论】:
标签: c# wpf xaml mvvm data-binding