我正在动态创建Label,Textbox和一个按钮。我需要Button与右侧的文本框显示在同一行。
这是我正在使用的代码:
Label lbl = new Label()
{
Content = "Some Label",
HorizontalAlignment = HorizontalAlignment.Left,
VerticalAlignment = VerticalAlignment.Top,
HorizontalContentAlignment = HorizontalAlignment.Center,
VerticalContentAlignment = VerticalAlignment.Center,
Height = 28,
};
TextBox tb = new TextBox()
{
Text = "Some Text",
IsReadOnly = true,
};
Button btn = new Button()
{
Content = "Click Me",
HorizontalAlignment = HorizontalAlignment.Left
Margin = new Thickness(tb.ActualWidth),
};
我正在将Text Margin指定给TextBox的右侧,但它仍然出现在文本框下的下一行。
我在这里做错了什么?
答案 0 :(得分:3)
您可以使用StackPanel
解决问题:
StackPanel spMain = new StackPanel() { Orientation = Orientation.Vertical };
Label lbl = new Label()
{
Content = "Some Label",
HorizontalAlignment = HorizontalAlignment.Left,
VerticalAlignment = VerticalAlignment.Top,
HorizontalContentAlignment = HorizontalAlignment.Center,
VerticalContentAlignment = VerticalAlignment.Center,
Height = 28,
};
StackPanel spInner = new StackPanel() { Orientation = Orientation.Horizontal };
TextBox tb = new TextBox()
{
Text = "Some Text",
IsReadOnly = true,
};
Button btn = new Button()
{
Content = "Click Me",
HorizontalAlignment = HorizontalAlignment.Left,
Margin = new Thickness(tb.ActualWidth),
};
spInner.Children.Add(tb);
spInner.Children.Add(btn);
spMain.Children.Add(lbl);
spMain.Children.Add(spInner);
您可以查看以下链接以获取更多信息:
http://msdn.microsoft.com/en-us/library/system.windows.controls.stackpanel.orientation.aspx
答案 1 :(得分:0)
这取决于您放置控件的页面内容是什么,是网格还是其他内容?
为什么不创建一个堆栈面板,它会根据需要正确地包含您的商品。
答案 2 :(得分:0)
为什么不将所有创建的控件放在StackPanel中,并将其Orientation设置为Horizontal。这样他们就会一直放在彼此旁边。
var stPanel = new StackPanel { Orientation = Orientation.Horizontal };
var button = new Button() { ... }
stPanel.Children.Add(button);
//And so on
编辑: kmatyaszek领先于我...... :)
答案 3 :(得分:0)
我认为如果你使用Button
实例中的Content方法会更好 private byte _count;
internal void FillbtnSubCat(Grid grid)
{
var myDefinition = new ColumnDefinition();
var myButton = new Button();
var myBlock = new TextBlock()
{
TextAlignment = TextAlignment.Center,
TextWrapping = TextWrapping.Wrap,
Text = "Some Text",
Margin = new Thickness(5, 10, 5, 10)
};
Grid.SetColumn(myButton, _count);
myButton.Margin = new Thickness(5, 10, 5, 25);
myButton.MinWidth = 30;
myButton.Content = myBlock;
myDefinition.Width = new GridLength(68);
grid.ColumnDefinitions.Add(myDefinition);
grid.Children.Add(myButton);
_count++;
}
XAML
<Grid Name="Grid1" Height="100" Width="auto">
</Grid>