我正在尝试在运行时在我的silverlight应用程序中执行这些操作:
1-创建图像列表 2-为其中任何一个定义自定义ContextMenu 我的代码如下:
void AddImageViewerToGridCells(Grid g)
{
for (int i = 1; i <= g.RowDefinitions.Count; i++)
for (int j = 1; j <= g.ColumnDefinitions.Count; j++)
{
var b = new Image();
b.Source = new BitmapImage(new Uri(@"Drop.jpg", UriKind.Relative));
b.SetValue(Image.NameProperty, "img" + i.ToString() + "_" + j.ToString());
b.Stretch = Stretch.Fill;
b.SetValue(Grid.RowProperty, i-1);
b.SetValue(Grid.ColumnProperty, j-1);
b.MouseRightButtonDown += b_MouseRightButtonDown;
g.Children.Add(b);
}
}
void b_MouseRightButtonDown(object sender, MouseButtonEventArgs e)
{
Image img = (Image)sender;
ContextMenu cm = new ContextMenu();
MenuItem mi1 = new MenuItem();
mi1.Header = "Add To List";
mi1.Click += mi1_Click;
cm.Items.Add(mi1);
MenuItem mi2 = new MenuItem();
mi2.Header = "Remove From List";
cm.Items.Add(mi2);
ContextMenuService.SetContextMenu(img, cm);
}
我看不到我的ContextMenu。 据我所知,我应该将dependencyObject传递给SetContextMenu方法,但是(就像我猜的那样)我的运行时控件不是依赖对象。
感谢您的帮助
答案 0 :(得分:0)
谢谢你没有回复我! 解决方案如下:
void AddImageViewerToGridCells(Grid g)
{
for (int i = 1; i <= g.RowDefinitions.Count; i++)
for (int j = 1; j <= g.ColumnDefinitions.Count; j++)
{
var b = new Image();
b.Source = new BitmapImage(new Uri(@"Drop.jpg", UriKind.Relative));
b.SetValue(Image.NameProperty, "img" + i.ToString() + "_" + j.ToString());
b.Stretch = Stretch.Fill;
b.SetValue(Grid.RowProperty, i-1);
b.SetValue(Grid.ColumnProperty, j-1);
ContextMenu cm = new ContextMenu();
ContextMenuService.SetContextMenu(b, cm);
cm.Opened+=cm_Opened;
//b.MouseRightButtonDown += b_MouseRightButtonDown;
g.Children.Add(b);
}
}
void cm_Opened(object sender, RoutedEventArgs e)
{
ContextMenu cm = (ContextMenu)sender;
cm.Items.Clear();
MenuItem mi1 = new MenuItem();
mi1.Header = "Add To List" + DateTime.Now.ToString();
mi1.Click += mi1_Click;
cm.Items.Add(mi1);
MenuItem mi2 = new MenuItem();
mi2.Header = "Remove From List" + DateTime.Now.ToString();
cm.Items.Add(mi2);
}