日期:2014-05-18  浏览次数:20827 次

wpf问题,ListBoxItem类对象中添加Canva模板,怎么继承ListBoxItem类,然后访问其受保护的AddChild方法,具体代码能用对象访问更好
如下代码:
 private void button1_Click(object sender, RoutedEventArgs e)
  { 
  ListBoxItem item = new ListBoxItem();
item.Height=20;
item.Width = 228;
   
 
Canvas canvas = new Canvas(); //面板
canvas.Width = 200;
canvas.Height = 20;  
   
 
Image myImage = new Image(); //图片
BitmapImage bi = new BitmapImage();
bi.BeginInit();
bi.UriSource = new Uri("boy.jpg", UriKind.Relative);
bi.EndInit();
myImage.Stretch = Stretch.Fill;
myImage.Margin = new Thickness(0,1,0,0);
myImage.Width = 20;
myImage.Height = 20;
myImage.Source = bi;  
  canvas.Children.Add(myImage); //将图片添加到面板中

 
item.MouseEnter += delegate //鼠标进入
{
item.Height = 50;
canvas.Height = 50;
myImage.Width = 50;
myImage.Height = 50;
};  
   
 
item.MouseLeave += delegate //鼠标离开
{
item.Height = 20;
canvas.Height = 20;
myImage.Width = 20;
myImage.Height = 20;
};
  此处怎么将canvas添加到item中呢???  
  listBox1.Items.Add(item); //将item添加到listBox中
  }
xaml文件中只定义了ListBox,无ListBoxItem,因为我想用代码实现添加ListBoxItem,但因为没有将canvas面板添加到item(即ListBoxItem对象)中,故看不到图片,请问高手,能不能将canvas添加到item中吗??用AddChild方法是受保护的,或其他方法,急。。。。

------解决方案--------------------
直接item.Content=canvas;不行吗?你试试,我用Silverlight试了一下可以的。
------解决方案--------------------
ls的方法貌似可以吧。直接item.Content=canvas。而且为什么要用代码来添加呢?求lz解答需求。