WPF中的GridView动态列宽

时间:2009-09-30 23:17:50

标签: wpf gridview listview

<Window x:Class="GridViewSample.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Window1" >
<Grid>
    <Grid.RowDefinitions>
        <RowDefinition/>
        <RowDefinition/>
    </Grid.RowDefinitions>
    <ListView Name="CheckoutList" Margin="0,0,8,0">
        <ListView.View>
            <GridView x:Name="CheckOutGridView">
                <GridView.ColumnHeaderContainerStyle>
                    <Style TargetType="{x:Type GridViewColumnHeader}">
                        <Setter Property="Visibility" Value="Collapsed"/>
                    </Style>
                </GridView.ColumnHeaderContainerStyle>
                <GridViewColumn>
                    <GridViewColumn.CellTemplate>
                        <DataTemplate>
                            <TextBlock> 
                                <Hyperlink >          
                                    <TextBlock Text="{Binding Path=Text}"/> 
                                </Hyperlink> 
                            </TextBlock>
                        </DataTemplate>
                    </GridViewColumn.CellTemplate>
                </GridViewColumn>
                <GridViewColumn>
                    <GridViewColumn.CellTemplate>
                        <DataTemplate>
                            <TextBlock> 
                                <Hyperlink>          
                                    <TextBlock Text="Remove"/> 
                                </Hyperlink> 
                            </TextBlock>
                        </DataTemplate>
                    </GridViewColumn.CellTemplate>
                </GridViewColumn>
            </GridView>
        </ListView.View>
    </ListView>

    <StackPanel Grid.Row="1">
        <Button Width="100" Height="25" Click="Button_Click" >name</Button>
        <Button Width="100" Height="25" Click="Button_Click1" >long name</Button>
    </StackPanel>
</Grid>

public partial class Window1 : Window
{
    class TextObject
    {
        private string _text;

        public TextObject(string Text)
        {
            _text = Text;
        }

        public string Text
        {
            get { return _text; }
            set { _text = value; }
        }
    }


    public Window1()
    {
        InitializeComponent();
    }

    private void Button_Click(object sender, RoutedEventArgs e)
    {
        CheckoutList.Items.Add(new TextObject("name"));
    }

    private void Button_Click1(object sender, RoutedEventArgs e)
    {
        CheckoutList.Items.Add(new TextObject("long name"));
    }

}

鉴于上面的样本按名称然后是长名称。为什么列不会调整大小以适应其内容?

1 个答案:

答案 0 :(得分:0)

尝试

<GridViewColumn Width="{x:Static System:Double.NaN}">

,其中

xmlns:System="clr-namespace:System;assembly=mscorlib"

这可以帮助您调整列的大小以适应标题内容。