简体   繁体   中英

How to bind Line.StrokeThickness property with Slider value in code behind?

I have a simple XAML file containing a canvas and a slider.

<Window x:Class="HitTesting.LineThickness"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="LineThickness" Height="300" Width="300">
    <DockPanel LastChildFill="True">
        <Slider x:Name="mySlider" DockPanel.Dock="Bottom" 
                Value="1" Maximum="2" Minimum="0.5">
        </Slider>
        <Canvas x:Name="myCanvas"></Canvas>
    </DockPanel>
</Window>

Now in my code behind, I want to bind the StrokeThickness property of the line to the slider value before adding it to canvas.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;

namespace HitTesting
{
    /// <summary>
    /// Interaction logic for LineThickness.xaml
    /// </summary>
    public partial class LineThickness : Window
    {
        public LineThickness()
        {
            InitializeComponent();
            Line myLine = new Line() { X1 = 10, Y1 = 40, X2 = 100, Y2 = 40 , Stroke= Brushes.Green};

            // Here, I want to bind the StrokeThickness property of myLine to mySlider value.

            myCanvas.Children.Add(myLine);

        }
    }
}

I searched in lots of questions here, but it seems I can't get it right. I appreciate it if you point me in the right direction.

Binding myBinding = new Binding("Value");
myBinding.Source = mySlider;
myLine.SetBinding(Shape.StrokeThicknessProperty, myBinding);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM