问题
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">
<ColumnDefinition 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.
回答1:
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!
回答2:
<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.
回答3:
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.
来源:https://stackoverflow.com/questions/1719093/cant-create-columns-in-my-wpf-grid