【发布时间】:2023-03-31 03:00:02
【问题描述】:
我有一个用户控件,里面有一个按钮。 UserControl 它的 DataContext 是我的模型之一,因此我可以绑定到它。但是,对于按钮,我希望能够从我的视图模型中调用一个方法。 ListBox 的 DataContext 就是这个 ViewModel。
因为我的 ContextMenu 也需要相同的 DataContext,所以我将它们绑定如下:
Command="{Binding Path=DataContext.AttendEventCommand, ElementName=EventListBox}"
调用 EventListBox 元素并使用其 DataContext 调用 AttendEventCommand。但是,我想从 UserControl 上的按钮调用 AttendEventCommand。我试过用同样的方法做,但遗憾的是它不起作用。
我的数据上下文是这样设置的:
DataContext="{Binding Path=EventList, Source={StaticResource Locator}}
我的列表框代码:
<ListBox x:Name="EventListBox" ItemsSource="{Binding Occurrences}" Margin="0,50,0,0" >
<ListBox.ItemTemplate>
<DataTemplate>
<Grid>
<uctl:EventListItem HorizontalAlignment="Stretch" VerticalAlignment="Stretch" Width="auto" Height="auto">
<toolkit:ContextMenuService.ContextMenu>
<toolkit:ContextMenu IsZoomEnabled="True" x:Name="ContextMenu">
<toolkit:MenuItem x:Name="Going" Header="{Binding AttendingText}" Command="{Binding Path=DataContext.AttendEventCommand, ElementName=EventListBox}" CommandParameter="{Binding}"/>
</toolkit:ContextMenu>
</toolkit:ContextMenuService.ContextMenu>
</uctl:EventListItem>
</Grid>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
还有我的 UserControl 按钮:
<Button Grid.RowSpan="3" Grid.Column="5" Opacity="0" Command="{Binding Path=DataContext.AttendEventCommand, ElementName=EventListBox}" CommandParameter="{Binding}"/>
【问题讨论】:
-
我在您的代码中没有看到您实际设置了 ListBox 的 DataContext。
ItemsSource != DataContext,因此您对命令的绑定永远不会起作用。 -
我省略了那部分代码,因为对我来说很明显我会首先设置 DataContext。我已将设置数据上下文的代码行添加到示例中以进行说明。
标签: xaml windows-phone-8