1

我需要将 UIElements 插入到运行时才会生成的 Grid 中。更具体地说,在确定需要显示多少元素后,我需要将 UIElements 添加到我创建的 RowDefinitions 中。有没有办法像在 XAML 中一样为 C# 中的对象控制 Grid.Row 和 Grid.Column 和 Grid.RowSpan?如果我要解决这个问题,请告诉我。我不能使用 StackPanel(我正在创建一个动态手风琴面板,它与动画混淆)。

现在发生的事情是我在运行时生成了 RowDefinition 的数量并将 UIElements 添加为子元素。这是行不通的,所有的 UIElements 最终都在第一行中,彼此重叠。

这是我正在尝试的示例:

public partial class Page : UserControl
{
    string[] _names = new string[] { "one", "two", "three" };
    public Page()
    {
        InitializeComponent();
        BuildGrid();
    }
    public void BuildGrid()
    {
        LayoutRoot.ShowGridLines = true;
        foreach (string s in _names)
        {
            LayoutRoot.RowDefinitions.Add(new RowDefinition());
            LayoutRoot.Children.Add(new Button());
        }
    }
}

谢谢!

4

3 回答 3

3

除了 Grid 不是真正适合该工作的工具(ListView 将是)之外,您需要告诉 Button 它属于哪一行。

public void BuildGrid()
{
    LayoutRoot.ShowGridLines = true;
    int rowIndex = 0;
    foreach (string s in _names)
    {
        LayoutRoot.RowDefinitions.Add(new RowDefinition());
        var btn = new Button()
        LayoutRoot.Children.Add(btn);
        Grid.SetRow(btn, rowIndex);
        rowIndex += 1;
    }
}
于 2009-02-11T23:14:34.657 回答
2

执行您要查找的操作的最佳方法是遵循以下模式:

页面.xaml:

<UserControl x:Class="SilverlightApplication1.Page"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:data="clr-namespace:System.Windows.Controls;assembly=System.Windows.Controls.Data"
    Width="400" Height="300">
    <Grid x:Name="LayoutRoot" Background="White">
        <data:DataGrid x:Name="DataGridTest" />
    </Grid>
</UserControl>

页面.xaml.cs:

public partial class Page : UserControl
    {
        string[] _names = new string[] { "one", "two", "three" };

        public Page()
        {
            InitializeComponent();
            BuildGrid();
        }

        public void BuildGrid()
        {
            DataGridTest.ItemsSource = _names;
        }
    }

这会根据字符串数组的内容动态构建行。将来更好的方法是使用ObservableCollection,其中 T 实现了INotifyPropertyChanged。如果您从集合中删除或添加项目以及 T 的属性发生更改,这将通知 DataGrid 更新其行。

要进一步自定义用于显示内容的 UIElements,您可以使用DataGridTemplateColumn

<data:DataGridTemplateColumn Header="Symbol">
    <data:DataGridTemplateColumn.CellTemplate>
        <DataTemplate>
            <TextBlock Text="{Binding PutNameOfPropertyHere}" />
        </DataTemplate>
    </data:DataGridTemplateColumn.CellTemplate>
</data:DataGridTemplateColumn>
于 2009-02-11T23:28:37.807 回答
0

我从未使用过这些东西,但您不应该将 Button 添加到 RowDefinitions 中,而不是 Children 中吗?(只是一个逻辑观察)

于 2009-02-11T22:45:37.473 回答