将上下文菜单添加到WrapPanel中的用户控件

时间:2011-04-27 20:58:39

标签: xaml windows-phone-7 binding contextmenu datacontext

我在WP7应用程序中从Silverlight Toolkit获得了一个WrapPanel。在我的代码隐藏中,我将自己的usercontrols添加到此wrappanel。每个用户控件都是一个显示航班信息的方块。

        <ScrollViewer x:Name="MyScrollViewer" HorizontalScrollBarVisibility="Auto" VerticalScrollBarVisibility="Auto" Height="307" VerticalAlignment="Bottom">
            <toolkit:WrapPanel x:Name="MonitoredWrapPanel" Margin="10,0,0,0" MinWidth="200" Width="{Binding ElementName=MyScrollViewer, Path=ViewportWidth}">
                <toolkit:ContextMenuService.ContextMenu>
                    <toolkit:ContextMenu x:Name="FlightContextMenuInGrid">
                        <toolkit:MenuItem Header="Stop monitoring flight" Click="MenuItem_Click" Tag="{Binding Path=FlightId}" />
                    </toolkit:ContextMenu>
                </toolkit:ContextMenuService.ContextMenu>
            </toolkit:WrapPanel>
        </ScrollViewer>

代码隐藏;

        foreach (var flight in Cache.MonitoredCombinedFlights)
        {
            FlightSquare square = new FlightSquare();
            square.DataContext = flight;
            square.Margin = new Thickness(10, 5, 10, 5);
            this.MonitoredWrapPanel.Children.Add(square);
        }

我的问题是MenuItem(对于ContextMenu)没有绑定到我的用户控件的DataContext的FlightId属性,而只是绑定到它自己。

如何让MenuItem了解它所在的FlightSquare?

2 个答案:

答案 0 :(得分:1)

显然,ContextMenu有不同的DataContext。每个方块中的绑定与此处的WrapPanel无关,您必须在代码隐藏中手动设置ContextMenu的绑定对象。

所以说,这是一个片段,展示如何绑定到代码隐藏中的属性(正是你需要做的):

Binding b = new Binding();
b.Source = ObjectToBindTo;
b.Path = new PropertyPath("PropertyToBindTo");

menu.SetBinding(DependencyPropertyToBind, b);

话虽如此,你的案子还有一个问题。 ContextMenu位于WrapPanel内 - 它与之相关,而不是与广场相关联。因此,您可能会更改使用ContextMenu进入方形实例而不是公共容器的方式。

答案 1 :(得分:1)

感谢Dennis的回答,这就是我最终的结果。我正在使用列表框与wrappanel结合使用以滚动方块列表。

<ListBox Height="311" HorizontalAlignment="Left" Margin="0,323,0,0" Name="MonitoredCombinedFlightsList" VerticalAlignment="Top" Width="450">
            <ListBox.ItemsPanel>
                <ItemsPanelTemplate>
                    <toolkit:WrapPanel x:Name="MonitoredWrapPanel" Margin="10,0,0,0" MinWidth="200">
                    </toolkit:WrapPanel>
                </ItemsPanelTemplate>
            </ListBox.ItemsPanel>
            <ListBox.ItemTemplate>
                <DataTemplate>
                    <Views:FlightSquare Margin="10,5,10,5">
                        <toolkit:ContextMenuService.ContextMenu>
                            <toolkit:ContextMenu x:Name="FlightContextMenuInGrid">
                                <toolkit:MenuItem Header="Stop monitoring flight" Click="MenuItem_Click" Tag="{Binding Path=FlightId}" />
                            </toolkit:ContextMenu>
                        </toolkit:ContextMenuService.ContextMenu>
                    </Views:FlightSquare>
                </DataTemplate>
            </ListBox.ItemTemplate>
        </ListBox>

在我的代码隐藏中;

MonitoredCombinedFlightsList.ItemsSource = Cache.MonitoredCombinedFlights;
相关问题