c# - 如何通过代码生成WPF控件

标签 c# .net wpf xaml

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

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

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 使用了一个叫做 attached properties 的时髦东西.因此,在您的 XAML 中,您可以这样写:

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

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

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

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

查看上面的链接 - 附加属性使 XAML 中的事情变得非常容易,但可能会牺牲直观的代码。

关于c# - 如何通过代码生成WPF控件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7586/

相关文章:

c# - 尝试在长时间运行的操作期间在 WPF 中显示 "please wait"消息

c# - 如何自动化测试 Outlook Add-In?

c# - Azure 服务总线 - 使用 OnMessage() 方法接收消息

c# - Xamarin iOS - Mapkit ArgumentNullException : Value cannot be null

c# - 对值类型的困惑

c# - 如何检查 IOException 是否为 Not-Enough-Disk-Space-Exception 类型?

c# - 无法解析 DateTime

c# - 如何以编程方式添加用户帐户策略?

WPF 数据绑定(bind)必应 map wpf api

c# - Caliburn Micro是否从版本1.1更改为1.5.1?