从 C# 代码创建 WPF 椭圆并通过鼠标移动它
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20581404/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Create WPF ellipse from C# code and move it by mouse
提问by aGGeRReS
I have a canvas, and I need to put an (for example) ellipse on it, not from XAML but from code. So I do
我有一个画布,我需要在它上面放一个(例如)椭圆,不是来自 XAML,而是来自代码。所以我做
Ellipse e1;
public MainWindow()
{
...
...
e1 = new Ellipse();
e1.Height = 100;
e1.Width = 100;
e1.Stroke = Brushes.Red;
e1.StrokeThickness = 5;
Canvas.SetLeft(e1,40);
Canvas.SetTop(e1,50);
e1.MouseDown += ellipse_MouseDown;
Canvas1.Children.Add(e1);
}
private void ellipse_MouseDown(object sender, MouseButtonEventArgs e)
{
Ellipse el = (Ellipse)sender;
el.Stroke = Brushes.Green;
buttonAdd.Content = "New_TEXT";
}
But it doesn't react on clicking. Anyway, I tried to add this ellipse_MouseDownmethod to ellipse that was created from XAML - and it works.
但它在点击时没有反应。无论如何,我尝试将此ellipse_MouseDown方法添加到从 XAML 创建的椭圆中 - 它有效。
<Canvas x:Name="Canvas1" HorizontalAlignment="Left" Height="421" Margin="10,10,0,0" VerticalAlignment="Top" Width="346">
<Ellipse x:Name="ellipse" Fill="#FFF4F4F5" HorizontalAlignment="Left" Height="111" Margin="117,152,0,0" Stroke="Black" VerticalAlignment="Top" Width="131" MouseDown="ellipse_MouseDown" MouseMove="ellipse_MouseMove" MouseUp="ellipse_MouseUp"/>
</Canvas>
Where can be a problem?
哪里会出问题?
UPD.
更新。
According to Rohit Vats's answer just add
根据 Rohit Vats 的回答,只需添加
e1.Fill = Brushes.Transparent;
or
e1.Fill = new SolidColorBrush((Color)ColorConverter
.ConvertFromString("#FFF4F4F5"));
'cause by default Fillis null which doesn't respond to mouse events
因为默认情况下Fill为 null 不响应鼠标事件
采纳答案by Rohit Vats
You need to set Fillto Transparentso that it can react to mouse events. By default Fillis nullwhich doesn't respond to mouse events -
您需要设置Fill为,Transparent以便它可以对鼠标事件做出反应。默认情况下Fill是null不响应鼠标事件-
e1.Stroke = Brushes.Red;
e1.Fill = Brushes.Transparent; <-- HERE
UPDATE
更新
As evident from XAML code, you are setting Fillto #FFF4F4F5but not setting it from code behind.
从 XAML 代码可以明显看出,您正在设置Fill为 #FFF4F4F5但不是从后面的代码中设置它。
e1.Fill = new SolidColorBrush((Color)ColorConverter
.ConvertFromString("#FFF4F4F5"));

