2017-02-12 99 views
0

這可能是一個愚蠢的問題,但我一直在尋找幾個小時才能得到答案。c#wpf刷新繪製的矩形畫布

我在我的主窗口中有一些矩形的畫布。一個文本框和一個按鈕,我想修改矩形的寬度

這就是我的WPF代碼(畫布):

<Canvas Name="IV" Width="{Binding Path=Länge}" Height="280" VerticalAlignment="Top" Margin="443,22,443.5,0"> 
     <Rectangle Canvas.Left="0" Canvas.Top="157.5" Width="{Binding Path=Länge}" Height="136" Name="rect3704" Fill="#FF999999" StrokeThickness="0.26458332"/> 
     <Rectangle Canvas.Left="0" Canvas.Top="20.5" Width="{Binding Path=Länge}" Height="136" Name="rect37047" Fill="#FF999999" StrokeThickness="0.26458332"/> 
     <Rectangle Canvas.Left="0" Canvas.Top="294.5" Width="{Binding Path=Länge}" Height="2.5" Name="rect3721" Fill="#FF999999" StrokeThickness="0.26458332"/> 
     <Rectangle Canvas.Left="0" Canvas.Top="17" Width="{Binding Path=Länge}" Height="2.5" Name="rect37217" Fill="#FF999999" StrokeThickness="0.26458332"/> 
     <Rectangle Canvas.Left="0" Canvas.Top="293.5" Width="{Binding Path=Länge}" Height="1" Name="rect3738" Fill="#FF333333" StrokeThickness="0.26458332"/> 
     <Rectangle Canvas.Left="0" Canvas.Top="156.5" Width="{Binding Path=Länge}" Height="1" Name="rect37386" Fill="#FF333333" StrokeThickness="0.26458332"/> 
     <Rectangle Canvas.Left="0" Canvas.Top="19.5" Width="{Binding Path=Länge}" Height="1" Name="rect373867" Fill="#FF333333" StrokeThickness="0.26458332"/> 
    </Canvas> 

我的C#代碼是

public partial class MainWindow : Window 
{ 
    public MainWindow() 
    { 
     InitializeComponent(); 
     this.DataContext = this; 

    } 
    public int Länge { get; set; } = 50; 



    public void button_Click(object sender, RoutedEventArgs e) 
    { 
     int Length = Convert.ToInt32(textBox.Text); 
     Länge = Length; 
     IV.InvalidateVisual(); 
     IV.InvalidateMeasure(); 
     IV.UpdateLayout(); 
     Action emptyDelegate = delegate { }; 
     IV.Dispatcher.Invoke(emptyDelegate, DispatcherPriority.Render); 
     MessageBox.Show(Convert.ToString(Länge)); 


    } 
} 

如果我在聲明變量'Länge'的地方修改起始值,矩形將採用指定的寬度。但通過按鈕更新除了消息框以外不會執行任何操作。正如你所看到的,我嘗試了Dispatcher.Invoke或canvas.InvalidateVisual()等一些soloutings,但沒有任何作品.. 對不起,新來的C#,只能通過做。

回答

0

使用DependencyPropety,它應該工作:

public int Länge 
    { 
     get { return (int)GetValue(LängeProperty); } 
     set { SetValue(LängeProperty, value); } 
    } 
    public static readonly DependencyProperty LängeProperty = 
     DependencyProperty.Register(
     "Länge ", typeof(int), typeof(MainWindow), new PropertyMetadata(50)); 

沒有必要無效措施或其他的東西:

public void button_Click(object sender, RoutedEventArgs e) 
{ 
    int Length = Convert.ToInt32(textBox.Text); 
    Länge = Length; 
    MessageBox.Show(Convert.ToString(Länge)); 
} 

另外請注意,您應該是否設置綁定的ElementName到當前控件或設置適當的DataContext。例如:

Width="{Binding ElementName=window, Path=Länge}" 

其中「window」是MainWindow.Xaml中MainWindow的名稱。

+0

看到[這個答案](http://stackoverflow.com/a/13956932/5615980) – Ron