2011-03-09 82 views
1

這裏我有一個標籤的XAML,但我想用C#定義它。如何動態定義此標籤?

任何人都可以幫我翻譯這到C#所以我可以在運行時創建此標籤?

它所在的畫布被稱爲left_canvas

<Label Canvas.Left="10" Canvas.Top="10" Canvas.Right="10" Height="30" Width="280" 
     Name="classname_label" FontFamily="MS Reference Sans Serif" FontSize="16" 
     FontWeight="Bold" Foreground="#FF3535A0" Content="Physics 101" /> 
+0

我沒有嘗試任何事情,因爲我不知道從哪裏開始 – Mike 2011-03-09 22:22:24

回答

1

有你go.Hope這個Helps.Working和測試

  BrushConverter bc = new BrushConverter(); 
      Label classname_label = new Label(); 
      classname_label.Content = "Physics 101"; 
      classname_label.Foreground = (Brush)bc.ConvertFrom("#FF3535A0"); 
      Canvas.SetLeft(classname_label, 10); 
      Canvas.SetTop(classname_label, 10); 
      Canvas.SetRight(classname_label, 10); 
      classname_label.Height=30; 
      classname_label.Width=280; 
      classname_label.FontFamily =new System.Windows.Media.FontFamily("MS Reference Sans Serif"); 
      classname_label.FontSize=16; 
      classname_label.FontWeight = System.Windows.FontWeights.Bold; 
      //Control you want to contain label 
      left_canvas.Controls.Add(classname_label); 
+0

謝謝!這是我得到的最有用的迴應!What's BrushConverter bc = new BrushConverter();做Forground? – Mike 2011-03-09 22:21:20

+0

歡迎。它用於將值轉換爲前景色 – 2011-03-10 09:50:16

0

您可以創建一個新的Label實例並簡單地設置您列出的所有屬性。

Label label = new Label(); 

label.Height = new Unit(30, UnitType.Pixel); 
... 
label.Content = "Physics 101"; 

//Set the dependency properties. 
label.SetValue(Canvas.Left, 10); 
... 
label.SetValue(Canvas.Top, 10); 

//Add it to the canvas. 
left_canvas.Controls.Add(label); 

或者這樣做,屬性名稱和依賴項屬性名稱可能不準確,因爲它來自內存。

1

你需要像這樣

Label label1 = new Label(); 
label1.Content = "Physics 101"; 
label1.Width = 280; 
label1.Height = 30; 
label1.SetValue(Canvas.LeftProperty, 10.0); 
left_canvas.Children.Add(label1); 
+0

怎麼辦我做fontFamily和fontWeight? – Mike 2011-03-09 22:06:10