Accessing WPF Component inside DataTemplate with Data Binding

I have several UI elements in DataTemplate

bound to ObservableCollection

Video objects. I want to call a method of the Video object when I click on the ContextMenuItem [Test] of the corresponding UI item.

Here is my XAML:

            <ItemsControl Name="VideoUIElment" >
                <ItemsControl.ItemTemplate>
                    <DataTemplate x:Uid="videoTemplate">
                        <Border CornerRadius="10" Padding="10, 10" Background="Silver" >
                            <TextBlock Name="label" Text="{Binding Name}" FontSize="30" Foreground="Black" VerticalAlignment="Center" HorizontalAlignment="Center">
                                <TextBlock.ContextMenu>
                                    <ContextMenu>
                                        <MenuItem Header="[TEST]" Name="Test" Click="Test_Click"/>
                                    </ContextMenu>
                                </TextBlock.ContextMenu>
                            </TextBlock>                              
                        </Border>
                    </DataTemplate>
      </ItemsControl.ItemTemplate>
                </ItemsControl>

      

Here is the collection:

    public MainWindow()
    {
        //ctor
        InitializeComponent();
        pathToLauncher = string.Empty;
        videos = new ObservableCollection<Video>();
        VideoUIElment.ItemsSource = videos;
    }

      

I know that for this I need to determine which Video object inside the collection is bound to a specific UI element I click and I could think of some trick to achieve this, but I would like to do it gracefully and intelligently. I've already seen some suggestions, but none of them seem to apply here. I guess it should be something lightweight, but I'm not very good at WPF yet.

+3


source to share


1 answer


Try the following:

MainWindow

public partial class MainWindow : Window
{
    ObservableCollection<Video> videos { get; set; }

    public MainWindow()
    {
        InitializeComponent();

        videos = new ObservableCollection<Video>
        {
            new Video {Name = "Video 1"},
            new Video {Name = "Video 2"},
            new Video {Name = "Video 3"}
        };

        VideoUIElment.ItemsSource = videos;
    }

    private void Test_Click(object sender, RoutedEventArgs e)
    {
        MenuItem item = (MenuItem)sender;

        Video video = (Video)item.DataContext;

        MessageBox.Show(video.VideoMethod());
    }
}

      



Video:

public class Video
{
    public string Name { get; set; }

    public string VideoMethod()
    {
        return string.Format(" Clicked {0}", Name);
    }
}

      

enter image description here

+3


source







All Articles