如何通过代码生成WPF控件

时间:2020-03-05 18:38:54  来源:igfitidea点击:

我试图了解XAML,并认为我会尝试编写一些代码。

尝试添加具有6 x 6列定义的网格,然后将文本块添加到其中一个网格单元格中。我似乎无法引用我想要的单元格。网格上没有可以添加文本块的方法。只有grid.children.add(object),没有单元格定义。

XAML:

<Page x:Class="WPF_Tester.Page1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="Page1"
    Loaded="Page_Loaded">

</Page>

C#:

private void Page_Loaded(object sender, RoutedEventArgs e)
{
    //create the structure
    Grid g = new Grid();
    g.ShowGridLines = true;
    g.Visibility = Visibility.Visible;

    //add columns
    for (int i = 0; i < 6; ++i)
    {
        ColumnDefinition cd = new ColumnDefinition();
        cd.Name = "Column" + i.ToString();

        g.ColumnDefinitions.Add(cd);
    }
    //add rows
    for (int i = 0; i < 6; ++i)
    {
        RowDefinition rd = new RowDefinition();
        rd.Name = "Row" + i.ToString();

        g.RowDefinitions.Add(rd);
    }
    TextBlock tb = new TextBlock();
    tb.Text = "Hello World";

    g.Children.Add(tb);
}

更新

这是令人毛骨悚然的地方:

  • 在XP上使用VS2008 Pro
  • WPFbrowser项目模板(已验证3.5)

我没有自动完成方法。

解决方案

回答

WPF利用了一种称为添加属性的时髦东西。因此,在XAML中,我们可以这样编写:

<TextBlock Grid.Row="0" Grid.Column="0" />

这将有效地将TextBlock移动到网格的单元格(0,0)中。

在代码中,这看起来有些奇怪。我相信会是这样的:

g.Children.Add(tb);
Grid.SetRow(tb, 0);
Grid.SetColumn(tb, 0);

请看一下添加属性上方的链接,该操作使XAML确实很容易完成,也许是以看起来直观的代码为代价的。

回答

单元格位置是一个添加属性,该值属于TextBlock而不是Grid。但是,由于属性本身属于Grid,因此我们需要使用属性定义字段或者提供的静态函数。

TextBlock tb = new TextBlock();
//
// Locate tb in the second row, third column.
// Row and column indices are zero-indexed, so this
// equates to row 1, column 2.
//
Grid.SetRow(tb, 1);
Grid.SetColumn(tb, 2);

回答

使用Grid类的添加属性。

在C#中:

Grid.SetRow( cell, rownumber )

在XAML中:

<TextBlock Grid.Row="1" />

另外,如果我们不使用动态网格,我会建议我们使用XAML标记语言。我知道,它具有学习曲线,但是一旦我们掌握了它,它将变得非常容易,尤其是如果我们要使用ControlTemplates和DataTemplates! ;)