Wpf 如何使用WrapPanel';数据模板
我有一个包装纸来展示一些元素。但我想使用DataTemplate来显示它们。 这是我的WrapPanel的XAML代码Wpf 如何使用WrapPanel';数据模板,wpf,wrappanel,Wpf,Wrappanel,我有一个包装纸来展示一些元素。但我想使用DataTemplate来显示它们。 这是我的WrapPanel的XAML代码 <WrapPanel Margin="10,57,12,10" x:Name="wrp1"> <WrapPanel.Resources> <DataTemplate DataType="{x:Type local:DateItem}"> <Grid Vertical
<WrapPanel Margin="10,57,12,10" x:Name="wrp1">
<WrapPanel.Resources>
<DataTemplate DataType="{x:Type local:DateItem}">
<Grid VerticalAlignment="Top" HorizontalAlignment="Stretch" Width="250" Height="300" Background="Blue">
<Label Content="{Binding Path=DateString}" FontSize="20" Cursor="Hand" Foreground="White" Background="Red" FontWeight="Bold" VerticalAlignment="Bottom" HorizontalAlignment="Left" Height="38" VerticalContentAlignment="Center" Padding="5,0,5,0"/>
</Grid>
</DataTemplate>
</WrapPanel.Resources>
</WrapPanel>
当窗口初始化时,我使用DateString参数创建一个DateItem,并将其作为子项添加到WrapPanel中
DateItem di = new DateItem();
di.DateString = "28.04.2014";
wrp1.Children.Add(di);
我认为一切都很好,但包裹面板没有显示任何内容:(
您能帮我解决这个问题吗?您将UI控件与用于定义数据表示的DataTemplates混淆了。要呈现数据,您必须设置控件的内容,这可以使用ContentControl完成。 此外,如果要添加多次,可以使用
ItemsControl
XAML:
DateItem:
如果您仍有兴趣将其呈现为控件,则必须定义默认样式,而不是默认模板 XAML: DateItem:
您好,谢谢您的回答,但它也不起作用。或者我无法使它起作用。我还有一件事,我将多次添加DateItem。我如何才能实现这一点?第一项对我来说绝对有效。无论如何,如果您仍然希望它呈现为控件,您需要默认样式。请检查第二种方法的答案中的更新。抱歉,第一项有效。好的,如何使用第一个示例多次添加DateItem?您可以使用ItemsControl。我已更新了答案。非常感谢!效果很好!
DateItem di = new DateItem();
di.DateString = "28.04.2014";
wrp1.Children.Add(di);
<WrapPanel x:Name="wrp1">
<WrapPanel.Resources>
<DataTemplate DataType="{x:Type local:DateItem}">
<Grid VerticalAlignment="Top" HorizontalAlignment="Stretch" Width="250"
Height="300" Background="Blue">
<Label Content="{Binding Path=DateString}" FontSize="20" Cursor="Hand"
Foreground="White" Background="Red" FontWeight="Bold"
VerticalAlignment="Bottom" HorizontalAlignment="Left"
Height="38" VerticalContentAlignment="Center"
Padding="5,0,5,0"/>
</Grid>
</DataTemplate>
</WrapPanel.Resources>
<ItemsControl x:Name="itemsControl"/>
</WrapPanel>
DateItem di = new DateItem();
di.DateString = "28.04.2014";
itemsControl.Items.Add(di);
public class DateItem
{
public string DateString { get; set; }
}
<WrapPanel x:Name="wrp1">
<WrapPanel.Resources>
<Style TargetType="{x:Type local:DateItem}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate>
<Grid VerticalAlignment="Top" HorizontalAlignment="Stretch"
Width="250" Height="300" Background="Blue">
<Label
Content="{Binding Path=DateString, RelativeSource=
{RelativeSource Mode=TemplatedParent}}"
FontSize="20" Cursor="Hand" Foreground="White"
Background="Red" FontWeight="Bold"
VerticalAlignment="Bottom"
HorizontalAlignment="Left"
Height="38" VerticalContentAlignment="Center"
Padding="5,0,5,0"/>
</Grid>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</WrapPanel.Resources>
</WrapPanel>
DateItem di = new DateItem();
di.DateString = "28.04.2014";
wrp1.Children.Add(di);
public class DateItem : Control
{
public string DateString { get; set; }
}