我有以下代码,基本上我无法弄清楚的是如何克隆整个网格并并排制作它们的空白副本....为了清楚地理解这与医院申请和网格与怀孕有关,所以当说“添加孩子”按钮时,应该在运行时创建一个全新的网格,感谢下面的帮助是一个可能对人们有所帮助的链接,因为我试过但不知道如何显示它
3 回答
You should put the object you are want to "clone" in a DataTemplate
and reference this template from an ItemsControl
, then when you need another grid add another item to the items control (or even better to the list the control is bound to) and the ItemsControl
will create a new grid and bind it the new object.
For an example take a look at this post on my blog.
Here is an example for this application (I left only the relevant parts and I didn't test it, so there are probably some typos there):
<Window ... >
<Window.Resources>
<DataTemplate x:Key="ChildTemplate">
<Grid>
...
<TextBlock Text="Delivery Date:" Grid.Column="0" Grid.Row="0"/>
<TextBox Text="{Binding DeliveryDate}" Grid.Column="1" Grid.Row="0"/>
<TextBlock Text="Delivery Time:" Grid.Column="0" Grid.Row="1"/>
<TextBox Text="{Binding DeliveryTime}" Grid.Column="1" Grid.Row="1"/>
...
</Grid>
</DataTemplate>
</Window.Resources>
...
<Button Content="AddChild" Click="AddChildClick"/>
...
<ScrollViewer>
<ItemsControl ItemsSource="{Binding AllChildren}" ItemsTemplate="{StaticResource ChildTemplate}">
<ItemsControl.PanelTemplate>
<ItemsPanelTemplate><StackPanel Orientation="Horizontal"/></ItemPanelTemplate>
<ItemsControl.PanelTemplate>
</ScrollViewer>
...
</Window>
And in cs:
- Set an object with all the form data as the Window's
DataContext
. I'll call this classPostDelveryData
. - Create another class with the repeating data. I'll call it
ChildDeliveryData
. - Add a property of type
ObservableCollection<ChildDeliveryData>
calledAllChildren
toPostDeliveryData
; it's important it'll beObservableCollection
and not any other type of collection. Now, for the magic:
private void AddChildClick(object sender, RoutedEvetnArgs e) { ((PostDeliveryData)DataContext).AllChildren.Add(new ChildDeliveryData()); }
And when you add the new item to the list another copy of the entire data template will be added.
If I am understanding correctly, you should create a UserControl, which wraps your Grid and subsequent controls inside. And use this User control anywhere you wanted to replicate that UI.
我不确定您在这里使用的方法是否正确。我会通过创建一个带有 Child 属性的“ChildGridControl”来解决这个问题,并让 Child 属性处理数据绑定。向 GUI 添加新的子项将涉及创建 ChildGridControl 的新实例。