2011-01-31 51 views
0

我有一个silverlight应用程序,但我现在需要使用百分比而不是使用固定高度和宽度来调整某些项目的大小。Silverlight,使用persentage计算形状高度和宽度

我对这个代码片段是:

private void drawCell(int row, int col, string label, Color fill) 
    { 
     Rectangle rect = new Rectangle(); 
     rect.Height = cellSize; 
     rect.Width = cellSize; 
     rect.StrokeThickness = 2; 
     rect.Stroke = new SolidColorBrush(Colors.DarkGray); 
     rect.Fill = new SolidColorBrush(fill); 

     Grid.Children.Add(rect); 
     Canvas.SetLeft(rect, col * cellSize); 
     Canvas.SetTop(rect, row * cellSize); 

     Rectangle innertec = new Rectangle(); 
     innertec.Height = cellSize - 30; 
     innertec.Width = cellSize - 10; 
     innertec.StrokeThickness = 1; 
     innertec.Stroke = new SolidColorBrush(Colors.Black); 
     innertec.Fill = new SolidColorBrush(fill); 
     innertec.Margin = new Thickness(5); 

     Grid.Children.Add(innertec); 
     Canvas.SetLeft(innertec, col * cellSize); 
     Canvas.SetTop(innertec, row * cellSize); 

     Border productLabelBorder = new Border(); 

     TextBlock productLabel = new TextBlock(); 
     productLabel.Height = cellSize - 60; 
     productLabel.Width = cellSize - 10; 
     productLabel.Margin = new Thickness(5, innertec.Height + 5, 0, 5); 
     productLabel.TextAlignment = TextAlignment.Center; 
     productLabel.TextWrapping = TextWrapping.NoWrap; 
     productLabel.TextTrimming = TextTrimming.WordEllipsis; 
     productLabel.Text = label; 
     ToolTipService.SetToolTip(productLabel, label); 

     productLabelBorder.Child = productLabel; 

     Grid.Children.Add(productLabelBorder); 
     Canvas.SetLeft(productLabelBorder, col * cellSize); 
     Canvas.SetTop(productLabelBorder, row * cellSize); 
    } 

我想要什么的代码做的是采取innertec和productLabel,并首先看CELLSIZE计算的高度和宽度(这是一个变量集其他地方),然后用百分比的cellSize创建这些对象。

原因是cellSize根据UI中的滑块更改大小。计算Canvas区域后,“单元格”会调整大小。

是否有可能以百分比计算这些值?

在此先感谢您的帮助。

回答

1

它看起来像你没有正确使用你的网格!我可以看到你正在向Grid中添加项目,然后尝试通过Canvas附加属性来定位它们。您正在混合两种不同的面板类型!

与画布,孩子们通过它们的顶部位置和左上角坐标

与电网儿童位于由Grid.Row和Grid.Column附加属性指示细胞内。

您可以使用“星号”宽度和高度来定义行/列的比例宽度和高度,以使网格单元占整个网格的某个百分比。例如,在标记,如果你想添加一个网格单元是整个网格大小的50%,你可以做到以下几点:

<Grid> 
    <Grid.ColumnDefinitions> 
    <ColumnDefinition Width="*"/> 
    <ColumnDefinition Width="*"/> 
    </Grid.ColumnDefinitions 

    <Button Grid.Column="1" Content="foo"/> 
</Grid> 

通过以上,该按钮将有一个宽度为50%整个网格宽度。

+0

对不起,我的命名约定很混乱。正如我最初使用网格,现在交给Canvas,但我已将Canvas x:name作为网格(它构建网格,但仍令人困惑)。 – Shaun 2011-02-02 09:18:21