1

我想我错过了一些重要的东西,但我就是想不通。我想让多个网格共享相同的列宽,因此我使用 sharedsizegroups,但我似乎无法让它工作。

xml:

<Window x:Class="WpfApplication1.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:local="clr-namespace:WpfApplication1"
        Title="MainWindow"
        Width="525"
        Height="350">
    <StackPanel x:Name="sg"
                local:exGrid.IsSharedSizeScope="True"
                Orientation="Vertical">
        <Button Click="Button_Click" Content="Click Me" />
    </StackPanel>
</Window>

后面的代码:

namespace WpfApplication1
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            sg.Children.Add(new exGrid("short", "loooooooooooooooooooooooooong", "a"));
            sg.Children.Add(new exGrid("veeeeeeeeeeeeeeeeeeery loooooooooooooooooooooooooong", "short", "a"));
        }
    }
}

exGrid.cs

namespace WpfApplication1
{
    class exGrid : Grid
    {
        public exGrid(string a, string b, string g)
        {
            this.SetValue(exGrid.IsSharedSizeScopeProperty, true);

            for (int i = 1; i <= 2; i++)
            {
                this.ColumnDefinitions.Add(new ColumnDefinition() { Width = GridLength.Auto, SharedSizeGroup = g });
            }

            this.SetValue(exGrid.ShowGridLinesProperty, true);

            TextBlock tx1 = new TextBlock();
            tx1.Text = a;

            TextBlock tx2 = new TextBlock();
            tx2.Text = b;

            tx1.SetValue(exGrid.ColumnProperty, 0);
            tx2.SetValue(exGrid.ColumnProperty, 1);

            this.Children.Add(tx1);
            this.Children.Add(tx2);
        }
    }
}
4

1 回答 1

2

请参阅 MSDN 示例:http: //msdn.microsoft.com/fr-fr/library/system.windows.controls.grid.issharedsizescope.aspx

您只需要在网格的容器上设置 IsSharedSizeScopeProperty,而不是在每个网格上:

namespace WpfApplication1
{
    class exGrid : Grid
    {
        public exGrid(string a, string b, string g)
        {
            // this.SetValue(exGrid.IsSharedSizeScopeProperty, true);

            for (int i = 1; i <= 2; i++)
            {
                this.ColumnDefinitions.Add(new ColumnDefinition() { Width = GridLength.Auto, SharedSizeGroup = g });
            }

            this.SetValue(exGrid.ShowGridLinesProperty, true);

            TextBlock tx1 = new TextBlock();
            tx1.Text = a;

            TextBlock tx2 = new TextBlock();
            tx2.Text = b;

            tx1.SetValue(exGrid.ColumnProperty, 0);
            tx2.SetValue(exGrid.ColumnProperty, 1);

            this.Children.Add(tx1);
            this.Children.Add(tx2);
        }
    }
}
于 2012-08-28T07:31:39.527 回答