【问题标题】:WPF grid questions - setting one up programmaticallyWPF 网格问题 - 以编程方式设置
【发布时间】:2014-10-08 05:55:54
【问题描述】:

我想显示一个图像网格。最初网格将是空的,然后随着图像从外部设备到达,可能会以随机顺序逐渐填充,即我可能会获取位置 (1,3) 的图像,然后是 (5,5) 等。

尺寸将在运行时知道,但在显示网格之前,我必须以编程方式设置它们,而不是在 XAML 中。

1. 我在网上找到的示例展示了如何在 XAML 中定义 Grid 行和列,但我如何在 C# 中以编程方式进行定义,即,如果指定了 5x4 Grid我希望用户最初看到一个空的 5x4 网格。

2. 如何以编程方式访问/更改各个网格位置的元素?当网格为空时,我希望最初在每个空白点显示一些东西(如“X”或彩色矩形),然后在到达时将其替换为实际图像。在 C# 中如何访问网格位置 (x,y) 以添加或更改其中的内容?

3 Grid 是否具有任何内在的滚动能力,或者我是否必须将它们包装在单独的滚动控件中,即,

<ScrollViewer>
    <Grid>
    </Grid> 
</ScrollViewer>

...如果我这样做,是否可以将滚动条设置为仅在需要时根据大小显示?

【问题讨论】:

  • 要不让滚动条一直显示,请移除滚动查看器。删除后它将按预期工作。

标签: c# wpf


【解决方案1】:
  1. 很简单,见msdn

        // Create the Grid
        Grid myGrid = new Grid();
        myGrid.Width = 250;
        myGrid.Height = 100;
        myGrid.HorizontalAlignment = HorizontalAlignment.Left;
        myGrid.VerticalAlignment = VerticalAlignment.Top;
        myGrid.ShowGridLines = true;
    
        // Define the Columns
        ColumnDefinition colDef1 = new ColumnDefinition();
        ColumnDefinition colDef2 = new ColumnDefinition();
        ColumnDefinition colDef3 = new ColumnDefinition();
        myGrid.ColumnDefinitions.Add(colDef1);
        myGrid.ColumnDefinitions.Add(colDef2);
        myGrid.ColumnDefinitions.Add(colDef3);
    
        // Define the Rows
        RowDefinition rowDef1 = new RowDefinition();
        RowDefinition rowDef2 = new RowDefinition();
        RowDefinition rowDef3 = new RowDefinition();
        RowDefinition rowDef4 = new RowDefinition();
        myGrid.RowDefinitions.Add(rowDef1);
        myGrid.RowDefinitions.Add(rowDef2);
        myGrid.RowDefinitions.Add(rowDef3);
        myGrid.RowDefinitions.Add(rowDef4);
    
        // Add the first text cell to the Grid
        TextBlock txt1 = new TextBlock();
        txt1.Text = "2005 Products Shipped";
        txt1.FontSize = 20; 
        txt1.FontWeight = FontWeights.Bold;
        Grid.SetColumnSpan(txt1, 3);
        Grid.SetRow(txt1, 0);
    
        ...
        myGrid.Children.Add(txt1);
        mainWindow.Content = myGrid
    
  2. Set网格位置,get它(获取更复杂)

  3. 在你的情况下,我可能会使用ListBoxWrapPanel。您将获得选择(多选?)和滚动作为奖励。搜索“wpf listbox wrappanel”,例如,here 是什么东西。

【讨论】:

  • 您的网格建议效果很好(得到了布局和网格线等)除了的文本。没有文本出现,我也不明白文本是如何插入的,因为你没有引用“myGrid”只是一般的 Grid 类,那么它怎么知道你的意思是那个特定的网格?我尝试用“myGrid”替换“Grid”并得到“无法通过实例引用访问;改为使用类型名称限定它”
  • Grid.SetRow()attached property。是的,你是对的,我的例子不完整,它错过了myGrid.Children.Add(txt1);,但你可以在 msdn 链接中找到完整的第一个问题答案(以及更多信息)。
猜你喜欢
  • 1970-01-01
  • 2012-12-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-12-10
  • 1970-01-01
相关资源
最近更新 更多