我很难在标题中描述的位置绑定(bind)到 ICommand。
首先,我在这个地方的 DataContext 是 Item
而不是我的 ViewModel,所以我需要以某种方式解决这个问题。我已经在我的 ItemClickCommand 上执行了此操作,但相同的解决方案将不起作用,因为:
其次,ContextMenu 不是窗口的一部分,也不是视觉或逻辑树的一部分。我不知道我需要实现什么woodoo 来解决这个问题。
View 模型:
public ICommand CopyTextCommand { get; private set; }
public Constructor()
{
CopyTextCommand = new RelayCommand(InsertToClopboard);
Initialize();
}
private void InsertToClopboard(object parameter)
{
// Want to get in here.
}
看法:
<Grid>
<Grid.RowDefinitions>
<RowDefinition />
<RowDefinition />
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<ListView Grid.Row="0" x:Name="MainListView" ItemsSource="{Binding Items}" Background="Transparent" BorderBrush="Transparent" Margin="0" HorizontalContentAlignment="Stretch">
<ListView.ItemTemplate>
<DataTemplate>
<Grid Margin="0" Visibility="{Binding GuiVisibility, Converter={StaticResource BoolToVisibility}}">
<Grid.InputBindings>
<MouseBinding Gesture="LeftClick"
Command="{Binding Path=DataContext.ItemClickCommand, RelativeSource={RelativeSource AncestorType={x:Type ListView}}}"
CommandParameter="{Binding}"/>
</Grid.InputBindings>
<Label ...
Content="{Binding PNR}" >
<Label.ContextMenu>
<ContextMenu>
<MenuItem
Name="MenuItemPnr"
Header="Copy"
Command="{Binding RelativeSource={RelativeSource Self}, Path=PlacementTarget.DataContext}" <--This does not work-->
CommandParameter="test" />
</ContextMenu>
</Label.ContextMenu>
</Label>
</Grid>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
</Grid>
编辑:
我试图在 en xaml 中添加一个具有正确绑定(bind)多个位置的标签,但是
MenuItem
的 PlacementTarget是 ContextMenu
.并且 ContextMenu 不知道正确的 DataContext。我该如何解决这个问题?
最佳答案
绑定(bind)Tag
Label
的属性(property)到 View 模型,然后绑定(bind) Command
MenuItem
的属性(property)到PlacementTarget
parent 的ContextMenu
:
<Label Content="{Binding PNR}" Tag="{Binding DataContext, RelativeSource={RelativeSource AncestorType=ListView}}">
<Label.ContextMenu>
<ContextMenu>
<MenuItem
Name="MenuItemPnr"
Header="Copy"
Command="{Binding Path=PlacementTarget.Tag.CopyTextCommand, RelativeSource={RelativeSource AncestorType=ContextMenu}}"
CommandParameter="test" />
</ContextMenu>
</Label.ContextMenu>
</Label>
关于c# - 在 ListView 中的网格中的标签中绑定(bind)到 ContextMenu 中的 ICommand 不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47135024/