开发者

Accessing ItemsSource source item

I'm creating an error list control similar to the in Visual Studio. Each error is represented by a class with three values: 开发者_开发技巧type (enum: Error/Warning/Message), text (string) and time (DateTime). The class has also two more read only getters: TimeString (returns time as HH:MM) and Icon (returns icon path based on type).

I have an ItemsControl bound to an ObservableCollection of objects via ItemsSource property.

I now want to implement a context menu for each of the items with two actions: Copy to clipboard and Delete from list.

How can I access the original item from the collection from the context menu item click handler?

Here is my XAML code:

    <ItemsControl Name="itemsControl"  ItemsSource="{Binding Items, ElementName=ConsoleWindow}">
        <ItemsControl.ItemTemplate>
            <DataTemplate DataType="Console.Items">
                <Border Name="itemBorder" BorderBrush="LightGray" BorderThickness="0,0,0,1" SnapsToDevicePixels="True" Padding="4">
                    <Border.ContextMenu>
                        <ContextMenu>
                            <MenuItem Header="Copy to clipboard" />
                            <MenuItem Header="Delete" />
                        </ContextMenu>
                    </Border.ContextMenu>
                    <DockPanel>
                        <Image Width="16" Height="16" Source="{Binding Icon}" Margin="0,3,4,0" VerticalAlignment="Top" DockPanel.Dock="Left" />
                        <TextBlock VerticalAlignment="Center" TextWrapping="Wrap" DockPanel.Dock="Left">
                            <Run Text="{Binding Text}" />
                            <TextBlock Foreground="Gray" FontSize="9">
                                <Run Text=" ("  /><Run Text="{Binding TimeString, Mode=OneWay}" /><Run Text=") " />
                            </TextBlock>
                        </TextBlock>
                    </DockPanel>

Thanks for any help


The DataContext property of any of the FrameworkElement derived elements (i.e. the TextBlock or Image or MenuItem) in the DataTemplate should have the original data item (the child automatically inherits the datasource of its parent unless otherwise set).

As part of the click event handler you get the element that is the source of the event, so cast it to MenuItem and check its DataContext property.


@slugster's answer would work. A more WPF-esque way of doing this would be to use a command for each menu item and set the parameter to {Binding}. WPF comes with commands for copy and possibly delete, so you might reuse those.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜