[英]Can't create Columns in my WPF Grid
I have this code for my very very basic WPF Project. 我有非常基本的WPF项目的代码。
<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'.
错误1无法将类型为“ColumnDefinition”的实例添加到“UIElementCollection”类型的集合中。 Only items of type 'UIElement' are allowed.
仅允许“UIElement”类型的项目。
you have to enclose it in a ColumnDefinitions collection. 你必须将它包含在ColumnDefinitions集合中。
<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: 在XAML中,这种表示法:
<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. 错误是网格将为子项获取UIElement项,而不是ColumnDefinition项。 This is because of the
<Container.Children>
implied in the shorthand notation being used. 这是因为正在使用的简写符号中隐含的
<Container.Children>
。
As other answers have stated, ColumnDefinition items need to be children of <Grid.ColumnDefinitions>
for the XAML to be valid. 正如其他答案所述,ColumnDefinition项需要是
<Grid.ColumnDefinitions>
子项才能使XAML有效。 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. 然后你也会有一个属性'Children'被设置多次构建错误,因为它的XAML语法使得
<Container.Children>
以简写符号隐含。 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. 这就是为什么
<ColumnDefinition>
项目需要明确包围的在<Grid.ColumnDefinitions>
收集,否则编译器试图采取<ColumnDefinition>
的暗示下<Grid.Children>
其预计自UIElement衍生品,因此错误的标签。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.