开发者

Can't create Columns in my WPF Grid

开发者 https://www.devze.com 2022-12-11 00:10 出处:网络
I have this code for my very very basic WPF Project. <Window x:Class=\"WpfApplication1.Window1\" xmlns=\"http://schemas.microsoft.com/winfx/2006/xaml/presentation\"

I have this code for my very very basic WPF Project.

<Window x:Class="WpfApplication1.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Window1" Height="300" Width="300">   

<Grid ShowGridLines="True">
    <Col开发者_JAVA技巧umnDefinition x:Name="LeftColumn"></ColumnDefinition>
</Grid>

However, the column definition line gives me an error:

Error 1 Cannot add instance of type 'ColumnDefinition' to a collection of type 'UIElementCollection'. Only items of type 'UIElement' are allowed.


you have to enclose it in a ColumnDefinitions collection.

<Grid Height="27">
    <Grid.ColumnDefinitions>
        <ColumnDefinition Width="*"/>
        <ColumnDefinition Width="*"/>
    </Grid.ColumnDefinitions>
</Grid>

Adding row definitions works the same way.

Enjoy!


<Window x:Class="WpfApplication1.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Window1" Height="300" Width="300">
<Grid ShowGridLines="True">
    <Grid.ColumnDefinitions>
    <ColumnDefinition x:Name="LeftColumn"></ColumnDefinition>
    </Grid.ColumnDefinitions>
</Grid>

I think this is what your looking for.


In XAML, this notation:

<Container>
    <ContentItem />
</Container>

Is shorthand for this:

<Container>
    <Container.Children>
        <ContentItem />
    </Container.Children>
</Container>

The error is saying the grid will take UIElement items for children, but not ColumnDefinition items. This is because of the <Container.Children> implied in the shorthand notation being used.

As other answers have stated, ColumnDefinition items need to be children of <Grid.ColumnDefinitions> for the XAML to be valid. However, it's good to know that if the markup were like this:

<Grid>
    <ColumnDefinition />
    <Grid.Children>
        ...
    </Grid.Children>
</Grid>

Then you would also have a The property 'Children' is set more than once build error, because it's XAML syntax that makes <Container.Children> be implied in the shorthand notation. That's why <ColumnDefinition> items need to be explicitly enclosed in the <Grid.ColumnDefinitions> collection, otherwise the compiler tries to take <ColumnDefinition> under an implied <Grid.Children> tag which expects items derived from UIElement, hence the error.

0

精彩评论

暂无评论...
验证码 换一张
取 消