none
用代码创建Canvas,Canvas不会充满父容器??? RRS feed

  • 问题

  • 用以下的XAML,创建的Canvas可以横向充满父容器。

    <Window x:Class="WpfApplication2.MainWindow"
            xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
            xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
            Title="MainWindow" Height="350" Width="525">
            <ContentControl Name="middleLowPlaceholder">
                <Grid>
                    <Grid.RowDefinitions>
                        <RowDefinition Height="Auto"/>
                        <RowDefinition Height="Auto"/>
                    </Grid.RowDefinitions>
                    <Grid.ColumnDefinitions>
                        <ColumnDefinition Width="Auto" />
                        <ColumnDefinition />
                        <ColumnDefinition Width="Auto" />
                    </Grid.ColumnDefinitions>
    
                    <Canvas Background="Red" Grid.Row="1" Grid.ColumnSpan="3" Height="20"/>
                </Grid>
            </ContentControl>
    </Window>

    但是我改用后台代码,就不行了。前台是这样的

    <Window x:Class="WpfApplication1.MainWindow"
            xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
            xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
            Title="MainWindow" Height="350" Width="525" Loaded="Window_Loaded">
        <ContentControl Name="middleLowPlaceholder"/>
    </Window>
    

    后台

            private void Window_Loaded(object sender, RoutedEventArgs e)
            {
                Grid DynamicPart = new Grid();
                DynamicPart.ColumnDefinitions.Add(new ColumnDefinition { Width = GridLength.Auto });
                DynamicPart.ColumnDefinitions.Add(new ColumnDefinition { Width = new GridLength() });
                DynamicPart.ColumnDefinitions.Add(new ColumnDefinition { Width = GridLength.Auto });
                DynamicPart.RowDefinitions.Add(new RowDefinition { Height = GridLength.Auto });
                DynamicPart.RowDefinitions.Add(new RowDefinition { Height = GridLength.Auto });
    
    
                Canvas c = new Canvas();
                c.Height = 20;
                c.Background = Brushes.Red;
                Grid.SetRow(c, 1);
                Grid.SetColumnSpan(c, 3);
                DynamicPart.Children.Add(c);
               
                middleLowPlaceholder.Content = DynamicPart;
            }

    这问题看了一晚上了,愣是没看出来,求救

    2012年5月10日 15:20

答案

  • 找到了。。。问题在于

     DynamicPart.ColumnDefinitions.Add(new ColumnDefinition { Width = new GridLength() });

    应该要 new GridLength(1,GridUnitType.Star)。

    结构的默认构造函数害死人啊。。。

    2012年5月11日 2:41

全部回复