2012-05-09 215 views
1

如何以編程方式生成佈局(XAML)?以編程方式生成佈局(XAML)

讓我說我有某種循環。而每之後我想與我的價值觀產生這樣的:

   <Grid Height="150" Name="grid1"> 
        <Grid.ColumnDefinitions> 
         <ColumnDefinition /> 
         <ColumnDefinition Width="200" /> 
        </Grid.ColumnDefinitions> 
        <Image Height="150" Name="image1" Stretch="Fill" Width="200" Grid.Column="1" Source="/Ilm;component/Images/testicon.png" HorizontalAlignment="Right" VerticalAlignment="Top" /> 
        <TextBlock Height="51" Name="textBlock1" Text="Paris" Margin="12,20,0,0" HorizontalAlignment="Left" VerticalAlignment="Top" FontSize="40" /> 
        <TextBlock FontSize="40" Height="51" HorizontalAlignment="Left" Margin="13,75,0,0" Name="textBlock2" Text="19°C" VerticalAlignment="Top" /> 
       </Grid> 
+0

你想添加新的行或產生整個事情? – scottheckel

+0

我想要根據需要生成整個事物...。 –

+0

好的,看看我的答案。我更新它來添加一個網格。 – scottheckel

回答

5

要添加一個新行到網格,你將需要添加一個新行定義,然後添加新的控件。這將是類同以下邏輯:

rowNumber = 0; // Set the current row that you are adding 
grid1.RowDefinitions.Add(new RowDefinition()); 

Image img = new Image(); 
img.Height = 150; 
img.Name = "image1"; 
img.Stretch = Stretch.Fill; 
img.Width = 200; 
img.HorizontalAlignment = HorizontalAlignment.Right; 
img.VerticalAlignment = VerticalAlignment.Top; 
// Set your image properties 
img.SetValue(Grid.RowProperty, rowNumber); 
img.SetValue(Grid.ColumnProperty, 1); 
grid1.Children.Add(img); 

TextBlock tb1 = new TextBlock(); 
// Set your text block properties 
tb1.SetValue(Grid.RowProperty, rowNumber); 
tb1.SetValue(Grid.ColumnProperty, 0); 
grid1.Children.Add(tb1); 

TextBlock tb2 = new TextBlock(); 
// Set your text block properties 
tb2.SetValue(Grid.RowProperty, rowNumber); 
tb2.SetValue(Grid.ColumnProperty, 0); 
grid1.Children.Add(tb2); 

你需要把你要設置在那裏我有意見,並提供(從零開始)正確的行數的屬性。

要添加整個事情...

Grid grid1 = new Grid(); 
grid1.Height = 150; 
grid1.Name = "grid1"; 
parentControl.Children.Add(grid1); // Note: parentControl is whatever control you are added this to 
grid1.ColumnDefinitions.Add(new ColumnDefinition()); 
grid1.ColumnDefinitions.Add(new ColumnDefinition { Width = 200}); 

// From here insert the code for adding a row that is provided above 

就是這樣。你只需要填寫我沒有提供的屬性。請記住,您的變量parentControl將有所不同。你沒有提供你將這些添加到什麼控制,所以它不清楚會是什麼。

+0

當我試圖將網格添加到「parentControl」它說「該參數不正確。」並沒有什麼比修復錯誤更有價值...比你長的回答當然..也許我應該尋找ItemsControl instaed ..因爲這對我來說太複雜了... –

+1

好吧,1小時後我明白了。 ..我讓你的代碼適合我的項目。你是老闆,besos! –

2

一種選擇是將所有代碼放在代碼隱藏中作爲Hexxagonal as suggested

另一種選擇和更傳統的方法是使用ItemsControl。通過將可視化佈局留在XAML中而不是代碼隱藏,這將允許更清晰的職責分離。

+0

是的。我應該提到他的編程方法不會是最好的。 – scottheckel

+0

毫無疑問。我只是想在OP不知道ItemsControl的情況下將其拋出。 –