我在按键盘按钮时尝试将图像添加到画布:
public MainWindow()
{
InitializeComponent();
}
public void OnKeyDownHandler(object sender, KeyEventArgs e)
{
Image img = new Image();
img.Source = new BitmapImage(new Uri("C:\\Users\\Public\\Pictures\\Sample Pictures\\Koala.jpg"));
Canvas.SetTop(img, 0);
Canvas.SetLeft(img, 0);
this.Content = img;
}
这是XAML:
<Canvas KeyDown="OnKeyDownHandler" HorizontalAlignment="Left" Height="166" Margin="118,89,0,0" VerticalAlignment="Top" Width="300"/>
但是当我按下按键时没有任何反应。如果我在MainWindow方法中放入相同的代码,它会加载图片。我哪里错了?
答案 0 :(得分:1)
您需要为画布指定一个名称并使画布具有焦点,然后在构造函数中关注它。这是代码段
<Canvas KeyDown="OnKeyDownHandler" Focusable="True" HorizontalAlignment="Left" Height="166" Margin="118,89,0,0" VerticalAlignment="Top" Width="300" Name="myCanvas"/>
代码背后:
public MainWindow()
{
InitializeComponent();
myCanvas.Focus(); //<-- Do this First
}
private void OnKeyDownHandler(object sender, KeyEventArgs e)
{
Image img = new Image();
img.Source = new BitmapImage(new Uri("C:\\Users\\Public\\Pictures\\Sample Pictures\\Koala.jpg"));
Canvas.SetTop(img, 0);
Canvas.SetLeft(img, 0);
this.Content = img;
}
答案 1 :(得分:1)
有几点:
MainCanvas.Children.Add(img);
this
时,你会引用类的实例 - 你的窗口,而不是画布。 this.Content=
与编写Content=
相同,并将img放在窗口上。这将直接在构造函数MainCanvas_MouseDown
。即使有背景,也不会触发KeyDown
。Focusable="True"
,&#39; keyDown&#39;也将开火(已经被其他人回答)XAML:
<Canvas Name="MainCanvas" Focusable="True" Background="AliceBlue" HorizontalAlignment="Left" Height="160" Margin="68,39,0,0" VerticalAlignment="Top" Width="192" KeyDown="MainCanvas_KeyDown" MouseDown="MainCanvas_MouseDown_1" >
代码:
public partial class MainWindow : Window
{
Image img = new Image { Source = new BitmapImage(new Uri("C:\\Users\\Public\\Pictures\\Koala.jpg")) };
public MainWindow()
{
InitializeComponent();
MainCanvas.Focus();
//this.Content = img;
//Content = img; //same as the above. you don't need to write "this".
}
private void button_Click(object sender, RoutedEventArgs e)
{// will work even if canvas has no background
MainCanvas.Children.Add(img);
}
private void MainCanvas_KeyDown(object sender, KeyEventArgs e)
{
//event will not fire. Canvas does not get the focus
//if you must have KeyDown trigger the event, you need MainCanvas.Focus() in the constructor, and Focusable="True" in the XAML.
MainCanvas.Children.Add(img);
}
private void MainCanvas_MouseDown_1(object sender, MouseButtonEventArgs e)
{
//This event will only fire if the canvas can get the focus: e.g. if it has some background.
MainCanvas.Children.Add(img); //canvas control has the name MainCanvas inside the xaml
//the below will work, but place the image on the window, because "this" means the class instance, not the method or event you are in.
//this.Content = img;
}
}
答案 2 :(得分:-1)
我认为您应该添加重量+高度并将图像添加到Canvas.Children
img.Width = value;
img.Height = value;
MyCanvas.Children.Add(img);