[英]How to get line size to refresh when textbox input changes
I have a line that gets drawn on canvas based on the user inputs for the length of the line. 我有一条线是根据用户输入的长度绘制在画布上的。 The line appears just fine but when I change the number in the textbox, a new line is just drawn on top of the first line without getting rid of the first one.
该行看起来很好,但是当我在文本框中更改数字时,仅在第一行的顶部绘制了一条新行,而没有摆脱第一行。
I've tried calling the method in different places with no luck. 我试过在没有运气的地方调用该方法。 Im a beginner so this is all new.
我是一个初学者,所以这是全新的。 I did not use MVVM for this project.
我没有为此项目使用MVVM。
Here is where the user enters the number: 用户在这里输入数字:
<TextBox PreviewTextInput="NumberValidationTextBox" Text="{Binding ycoord}" Name="y" TextChanged="Y_TextChanged" Height="20" Width="40" Grid.Row="2" Grid.Column="2"/>
Here's my C#: 这是我的C#:
private double yval;
public double ycoord
{
get => yval;
set
{
yval = value;
heightline();
}
}
public void heightline()
{
Line heightline = new Line();
heightline.Stroke = new SolidColorBrush(Colors.SteelBlue);
heightline.StrokeThickness = 2;
heightline.X1 = 510;
heightline.Y1 = 110;
heightline.X2 = 510;
heightline.Y2 = 110 + rect.Height;
main.Children.Add(heightline);
}
rect.Height is another method that uses the same textbox to create a rectangle but it resizes based on aspect ratio so I need to use rect.Height to draw the line in order to maintain the same height as the rectangle. rect.Height是另一个使用相同文本框创建矩形的方法,但是它会根据宽高比调整大小,因此我需要使用rect.Height绘制线条以保持与矩形相同的高度。
expected results are the line refreshes automatically to the new size as soon as the textbox has been changed. 预期的结果是,文本框更改后,该行会自动刷新为新的大小。 This does happen, but the old one stays on the canvas underneath the new line.
确实发生了,但是旧的仍然停留在新行下面的画布上。
You can try to find the line in the canvas and if does not exist add it, otherwise update it: 您可以尝试在画布中找到该行,如果不存在,请添加该行,否则进行更新:
public void heightline()
{
List<UIElement> uIElements = mycanvas.Children.Cast<UIElement>().ToList();
UIElement heightline = uIElements.Where(p => p.Uid == "myLine").FirstOrDefault();
if (heightline == null)
{
heightline = new Line();
heightline.Uid = "myLine";
}
heightline.Stroke = new SolidColorBrush(Colors.SteelBlue);
heightline.StrokeThickness = 2;
heightline.X1 = 510;
heightline.Y1 = 110;
heightline.X2 = 510;
heightline.Y2 = 110 + rect.Height;
if(uIElements.Count == 0)
{
mycanvas.Children.Add(heightline);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.