WPF绘制线段(直线)的方法

(1)如果是绘制单根直线,那么使用Line类。

Line类继承自Shape,Shape继承自FrameworkElement,FrameworkElement继承自UIElement,所以Panel可以直接调用.Children.Add()方法添加Line。

首先在Window中添加一个Canvas,名字是canvas1,那么添加直线的代码就是

                Line myLine = new Line();
                myLine = new Line();
                myLine.Stroke = System.Windows.Media.Brushes.LightSteelBlue;
                myLine.X1 = 1;
                myLine.X2 = 50;
                myLine.Y1 = 1;
                myLine.Y2 = 50;
                myLine.HorizontalAlignment = HorizontalAlignment.Left;
                myLine.VerticalAlignment = VerticalAlignment.Center;
                this.canvas1.Children.Add(myLine);

其中
myLine.Stroke = System.Windows.Media.Brushes.LightSteelBlue;

很重要,用来选择画刷。如果没有的话话出来的线就是白色的。

另外

myLine.StrokeThickness = 2;

是用来控制画刷的粗细的。


(二)如果用来绘制一连串连续的折线段,那么上述方法就不适合了。


  • 1
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
WPF 中可以通过路由实现控件的联动,比如当一个控件的值改变时,另一个控件的值也跟着改变。 具体实现可以通过以下步骤: 1. 使用 `DependencyProperty` 定义一个依赖属性,用于存储控件的值。 2. 在控件的 XAML 中,将该依赖属性绑定到控件的值属性上。 3. 使用 `PropertyChangedCallback` 方法监听值的变化,在方法中通过路由查找找到需要联动的控件,并将其值更新。 以下是一个实现两个 `TextBox` 联动的示例代码: ``` public class TextBoxHelper { public static readonly DependencyProperty TextProperty = DependencyProperty.RegisterAttached("Text", typeof(string), typeof(TextBoxHelper), new PropertyMetadata(null, OnTextChanged)); public static string GetText(DependencyObject obj) { return (string)obj.GetValue(TextProperty); } public static void SetText(DependencyObject obj, string value) { obj.SetValue(TextProperty, value); } private static void OnTextChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { // 获取路由根节点 var root = (FrameworkElement)Application.Current.MainWindow; // 查找需要联动的控件 var textBoxes = FindVisualChildren<TextBox>(root); // 更新控件的值 foreach (var textBox in textBoxes) { if (textBox != d) { textBox.Text = e.NewValue as string; } } } private static IEnumerable<T> FindVisualChildren<T>(DependencyObject obj) where T : DependencyObject { if (obj != null) { for (int i = 0; i < VisualTreeHelper.GetChildrenCount(obj); i++) { DependencyObject child = VisualTreeHelper.GetChild(obj, i); if (child is T t) { yield return t; } foreach (T childOfChild in FindVisualChildren<T>(child)) { yield return childOfChild; } } } } } ``` 在 XAML 中,将 `Text` 属性绑定到 `TextBoxHelper` 中定义的依赖属性,实现联动: ``` <TextBox local:TextBoxHelper.Text="{Binding Text1, Mode=TwoWay}" /> <TextBox local:TextBoxHelper.Text="{Binding Text2, Mode=TwoWay}" /> ``` 其中,`Text1` 和 `Text2` 分别为两个 `TextBox` 的值。 这样,当一个 `TextBox` 的值改变时,另一个 `TextBox` 的值也会跟着改变。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值