bak*_*408 3 c# data-binding wpf xaml
我正在努力从 DataTemplate/ContextMenu 控件绑定到父 DataContext。我已经尝试过此处和此处提到的解决方案,但没有运气。我无法绑定到属性或命令 - 不会引发异常,但不会调用命令并且属性设置为 null。
这是我的代码示例(尽可能简化):
<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>
Run Code Online (Sandbox Code Playgroud)
我也尝试通过RelativeSource 将 Tag 属性与 Window 的 DataContext 绑定(以及在其他主题中找到的其他可能的解决方案),但没有任何反应。我的方法一定有明显的错误。
您在 Grid 中找不到 PlacementTarget 属性。像这样改变你的绑定,
<MenuItem Header="{Binding PlacementTarget.Tag.test,RelativeSource={RelativeSource Mode=FindAncestor,AncestorType=ContextMenu}}" />
Run Code Online (Sandbox Code Playgroud)
或者像,
<MenuItem Header="{Binding Parent.PlacementTarget.Tag.test,RelativeSource={RelativeSource Self}}" />
Run Code Online (Sandbox Code Playgroud)
另外要访问 ViewModel 的命令,请访问 ListBox 的 DataContext 而不是 ListBoxItem,
<Grid Margin="5" Width="110" ToolTip="{Binding Path=TooltipInfo}" MouseDown="FileItemClick" Tag="{Binding DataContext,RelativeSource={RelativeSource Mode= FindAncestor, AncestorType=ListBox}}">
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
2518 次 |
最近记录: |