2014-02-08 71 views
2

我有一個簡單的XAML文件,其中包含一個畫布和一個滑塊。如何將Line.StrokeThickness屬性與代碼後面的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> 

現在在我後面的代碼,我想將它添加到畫布前行至滑塊值的StrokeThickness屬性綁定。

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

     } 
    } 
} 

我在這裏搜索了很多的問題,但似乎我不明白。我感謝你,如果你指向正確的方向。

回答

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

這工作,非常感謝你。如何使用此方法將它綁定到滑塊的(1/Value)?可能嗎?我想要定義相對於滑塊值倒數的線條粗細,以便稍後使用滑塊縮放時保持不變。 – Vahid

+0

如果添加另一個實現IValueConverter的類,可以使用'Binding.Converter' - 檢查:http://msdn.microsoft.com/en-us/library/ms742863(v=vs.110).aspx –

+0

@ user2720372謝謝,我現在就來看看。我是wpf的新手,這很棒,但它讓我覺得我對編程一無所知:p – Vahid

相關問題