【发布时间】:2015-07-06 08:16:00
【问题描述】:
我正在我的grid 上动态创建CheckBoxes。现在我还想动态设置margin(尊重CheckBox),但不确定最好的方法是什么。
例如,
- 如果只有一个
CheckBox,那么margin应该是{5,0,0,0} - 如果有两个
CheckBoxes,那么第一个应该有{5,0,0,0},第二个应该有{10,0,0,0},依此类推。 我担心左边距。这些复选框的创建基于List<String>。
XAML:
<Grid x:Name="SynonymsGrid" Grid.Column="2" Margin="0,35,0,0" >
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
</Grid.RowDefinitions>
</Grid>
代码隐藏:
List<String> names = new List<string>() { "one", "two", "three" };
foreach (var name in names)
{
CheckBox chb = new CheckBox();
chb.Content = name;
chb.Margin = new System.Windows.Thickness { Left = 5, Top = 0, Right = 0, Bottom = 0 };
synonymsGrid.Children.Add(chb);
}
上面的代码会将所有复选框设置在一个显而易见的位置。我想过使用for loop,但不确定什么是最好的方法。
解决方案:
for (int i = 0; i < names.Count; i++)
{
CheckBox chb = new CheckBox();
chb.Content = names[i];
chb.Margin = new System.Windows.Thickness { Left = i * 150, Top = 0, Right = 0, Bottom = 0 };
synonymsGrid.Children.Add(chb);
}
【问题讨论】:
-
我找到了解决方案并更新了答案。感谢收看。
-
@OmegaMan 感谢您的编辑。下次我会记住这些。
标签: c# silverlight margin