1

我正在动态创建标签、文本框和按钮。我需要 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),
    };

我将按钮边距分配给 TextBox 的右侧,但它仍然出现在文本框下的下一行中。

我在这里做错了什么?

4

4 回答 4

4

您可以使用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

于 2013-01-30T15:42:40.370 回答
0

这取决于您放置控件的页面内容是什么,是网格还是其他?

为什么不创建一个堆栈面板,它会根据需要以时尚的方式正确包含您的项目。

于 2013-01-30T15:41:51.727 回答
0

为什么不将所有创建的控件放在 StackPanel 中,并将其方向设置为水平。这样,它们将始终彼此相邻放置。

var stPanel = new StackPanel { Orientation = Orientation.Horizontal };
var button = new Button() { ... }
stPanel.Children.Add(button);
//And so on

编辑: kmatyaszek 在我前面... :)

于 2013-01-30T15:45:18.540 回答
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>
于 2016-04-24T21:50:12.500 回答