我在绑定到Video对象的ObservableCollection的DataTemplate中有几个UI元素.当我单击相应UI元素的ContextMenuItem [测试]时,我想调用Video对象的方法.
这是我的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>
这是集合:
public MainWindow()
{
//ctor
InitializeComponent();
pathToLauncher = string.Empty;
videos = new ObservableCollection<Video>();
VideoUIElment.ItemsSource = videos;
}
我知道,要执行此操作,我必须确定集合中的哪个Video对象绑定到我单击的特定UI元素,我可以想出一些技巧来实现此目的,但是我想在一个优美而智能的方式.
我已经看到了一些建议,但似乎其中没有一个适用.我想这应该很容易,但是我对WPF并不十分了解.
解决方法:
尝试这个:
主窗口:
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());
}
}
视频:
public class Video
{
public string Name { get; set; }
public string VideoMethod()
{
return string.Format(" Clicked {0}", Name);
}
}