gpt4 book ai didi

c# - 从 ContextMenu 绑定(bind)到父 DataContext

转载 作者:行者123 更新时间:2023-12-05 01:43:27 25 4
gpt4 key购买 nike

我正在努力从 DataTemplate/ContextMenu 控件绑定(bind)到父 DataContext。我已经尝试过提到的解决方案 herehere但没有运气。我无法绑定(bind)到属性或命令 - 没有抛出异常,但没有调用命令并且属性设置为空。

这是我的代码示例(尽可能简化):

<Metro:MetroWindow ...>
<Window.DataContext>
<local:MyViewModel />
</Window.DataContext>
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="1*" />
<ColumnDefinition Width="10*" />
<ColumnDefinition Width="1*" />
</Grid.ColumnDefinitions>
<StackPanel ... />
<Grid Grid.Column="1">
<Border ... />
<ListBox x:Name="FileList" ItemsSource="{Binding AddedFiles}" Margin="5,5,5,5" SelectionMode="Multiple" SelectionChanged="ItemsSelectionChanged">
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<WrapPanel MaxWidth="700" IsItemsHost="True"/>
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
<ItemsControl.ItemTemplate>
<DataTemplate DataType="{x:Type local:FileListItem}">
<Grid Margin="5" Width="110" ToolTip="{Binding Path=TooltipInfo}" MouseDown="FileItemClick" Tag="{Binding DataContext,RelativeSource={RelativeSource Mode=Self}}">
<Grid.ContextMenu>
<ContextMenu>
<MenuItem Header="{Binding PlacementTarget.Tag.test,RelativeSource={RelativeSource Mode=FindAncestor,AncestorType=ContextMenu}}" />
<MenuItem Header="Test command" Command="{Binding PlacementTarget.Tag.CloseCommand, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=ContextMenu}}"/>
</ContextMenu>
</Grid.ContextMenu>
<Grid.RowDefinitions ... />
<StackPanel ...(Databinding works here!) />
<TextBlock ... (Databinding works here!) />
<Rectangle ... (Databinding works here!) />
</Grid>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ListBox>
</Grid>
</Grid>

我也尝试通过 RelativeSource 将 Tag 属性与 Window 的 DataContext 绑定(bind)(以及在其他主题中找到的其他可能的解决方案),但没有任何反应。我的方法肯定有明显错误。

最佳答案

您在 Grid 中找不到 PlacementTarget 属性。像这样改变你的绑定(bind),

 <MenuItem Header="{Binding PlacementTarget.Tag.test,RelativeSource={RelativeSource Mode=FindAncestor,AncestorType=ContextMenu}}" />

或者喜欢,

<MenuItem Header="{Binding Parent.PlacementTarget.Tag.test,RelativeSource={RelativeSource Self}}" />

另外,要访问 ViewModel 的命令,请访问 ListBox 的 DataContext 而不是 ListBoxItem,

 <Grid Margin="5" Width="110" ToolTip="{Binding Path=TooltipInfo}" MouseDown="FileItemClick" Tag="{Binding DataContext,RelativeSource={RelativeSource Mode= FindAncestor, AncestorType=ListBox}}">

关于c# - 从 ContextMenu 绑定(bind)到父 DataContext,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49381440/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com