2011-05-11 137 views
0

我正在學習WPF並有這個簡單的問題。
如何設置填充顏色到屬性vi XAML?從屬性填充顏色通過XAML

<Rectangle Fill="{Binding Path=BackgroundColorf}" 
      Height="112" Margin="0,84,0,0" VerticalAlignment="Top" 
      Width="116"/> 
public partial class MainWindow : Window 
{ 

     /// <summary> 
     /// Gets or sets the BackgroundColor. 
     /// </summary> 
    public SolidColorBrush BackgroundColorf 
    { 
     get; 
     set; 
    } 

    public MainWindow() 
    { 
     this.InitializeComponent(); 
     BackgroundColorf = new SolidColorBrush(Colors.Red); 
    } 
} 
+0

你設置了DataContext嗎? – PaulB 2011-05-11 10:36:13

+0

不,我沒有......我應該如何設置datacontext? – 2011-05-11 11:09:20

+3

請閱讀[數據綁定概述](http://msdn.microsoft.com/zh-cn/library/ms752347.aspx),這是您應該知道的基本內容。 – 2011-05-11 11:38:15

回答

1

這樣設置

public MainWindow() 
    { 
     this.DataContext = this;  
     this.InitializeComponent(); 
     BackgroundColorf = new SolidColorBrush(Colors.Red); 
    } 

這應該work.But有更多的小製作做了你的DataContext WPF應用程序可擴展通知等,依賴屬性etc.I建議你去通過WPF數據綁定架構的continuing.Go前基本通過HB在評論

+0

你太快了^^+1 – blindmeis 2011-05-11 11:48:48

+0

@blindmeis謝謝。因爲很多其他人;) – biju 2011-05-11 11:54:20

1

,讓你去...

名稱添加到矩形

<Rectangle x:Name="MyRect" Fill="{Binding Path=BackgroundColorf}" Height="112" ... 

然後在代碼

InitializeComponent(); 
MyRect.DataContext = this; 
BackgroundColorf = new SolidColorBrush(Colors.Red); 

不TH Ë最好的做事方式 - 但至少你將有一個紅色的矩形:)

+0

我的鍍鉻太慢^^ +1 – blindmeis 2011-05-11 11:49:57

0

發佈的鏈接,如果你加入這個您的示例將工作

public MainWindow() 
{ 
    this.InitializeComponent(); 
    this.DataContext = this; 
    BackgroundColorf = new SolidColorBrush(Colors.Red); 
} 

但你應該真的在一些wpf書籍或網站上獲得基礎知識。

非常好的一本書是來自Adam Nathan的「WPF 4 Unleashed」。