c# - 如何在代码后面将 Line.StrokeThickness 属性与 Slider 值绑定(bind)?

标签 c# wpf xaml

我有一个简单的 XAML 文件,其中包含 Canvas 和 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>

现在,在后面的代码中,我想在将线条添加到 Canvas 之前将线条的 StrokeThickness 属性绑定(bind)到 slider 值。

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);

        }
    }
}

我在这里搜索了很多问题,但似乎找不到正确的答案。如果您为我指出正确的方向,我将不胜感激。

最佳答案

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

关于c# - 如何在代码后面将 Line.StrokeThickness 属性与 Slider 值绑定(bind)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21651420/

相关文章:

c# 将ftp服务器上的图片直接加载到图片框中,无需下载

wpf - ContentControl 崩溃中的绑定(bind)

c# - "The subprocess making the call can not access this object because the owner is another thread"异常异步/等待 WPF C#

c# - 结合单例模式和存储库模式

c# - OpenRasta 可以与现有的 Web 应用程序一起运行吗?

c# - WPF 进度条在几条之后停止

wpf - 为什么在此 Xaml 中忽略 StringFormat?

c# - 在普通的 ContentTemplate 中使用 AdornedElementPlaceholder

c# - 检查驱动器是否存在(字符串路径)

c# - 某些设备的 UWP 中的 XAML 梯度问题