我想以编程方式将控制树复制到另一个Grid列,并且我希望在每个播放器中使用P2,P3,P4更改某些控件名称中的P1,因此我有4个类似的块来显示每个玩家的信息。
数据是当前设置的,所以我只需要替换播放器ID:
public void ReadPlayer(Player player) {
GetControl<Label>(player, "lbl", "Points").Content = String.Format("{0} / 8", player.Points);
GetControl<Slider>(player, "sld", "Points").Value = player.Points;
GetControl<TextBox>(player, "txt", "PositionX").Text = player.PosX + "";
GetControl<TextBox>(player, "txt", "PositionY").Text = player.PosY + "";
GetControl<TextBox>(player, "txt", "PositionZ").Text = player.PosZ + "";
}
这是XAML:
<GroupBox Header="Player 1" Name="grpP1" Margin="0,0,0,0">
<Grid>
<GroupBox Header="Points" Height="122" Margin="6,6,6,0" VerticalAlignment="Top">
<Grid>
<Label Height="28" Margin="6,0" Name="lblP1Points" VerticalAlignment="Top" HorizontalContentAlignment="Center" Width="199" Content="0 / 8" />
<Slider Height="34" Margin="6,34,6,0" Name="sldP1Points" VerticalAlignment="Top" SmallChange="1" Minimum="0" Maximum="8" TickPlacement="Both" />
<CheckBox Content="Freeze" Height="16" Margin="6,74,6,0" Name="chkP1Points" VerticalAlignment="Top" HorizontalContentAlignment="Left" />
</Grid>
</GroupBox>
<GroupBox Header="Position" Height="121" Margin="6,134,6,0" VerticalAlignment="Top">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="25" />
<ColumnDefinition Width="*" />
<ColumnDefinition Width="62" />
</Grid.ColumnDefinitions>
<Label Content="X" Height="28" Margin="6,6,0,0" VerticalAlignment="Top" HorizontalAlignment="Left" Width="19" />
<TextBox Height="23" Margin="6,9,6,0" Name="txtP1PositionX" VerticalAlignment="Top" Grid.Column="1" />
<CheckBox Content="Freeze" Height="20" Margin="0,12,0,0" Name="chkP1PositionX" VerticalAlignment="Top" HorizontalAlignment="Left" Width="64" Grid.Column="2" />
<Label Content="Y" Height="28" HorizontalAlignment="Left" Margin="6,35,0,0" VerticalAlignment="Top" Width="19" />
<TextBox Height="23" Margin="6,39,6,0" Name="txtP1PositionY" VerticalAlignment="Top" Grid.Column="1" />
<CheckBox Content="Freeze" Height="20" HorizontalAlignment="Left" Margin="0,41,0,0" Name="chkP1PositionY" VerticalAlignment="Top" Width="64" Grid.Column="2" />
<Label Content="Z" Height="28" HorizontalAlignment="Left" Margin="6,64,0,0" VerticalAlignment="Top" Width="19" />
<TextBox Height="23" Margin="6,68,6,0" Name="txtP1PositionZ" VerticalAlignment="Top" Grid.Column="1" />
<CheckBox Content="Freeze" Height="20" HorizontalAlignment="Left" Margin="0,70,0,0" Name="chkP1PositionZ" VerticalAlignment="Top" Width="64" Grid.Column="2" />
</Grid>
</GroupBox>
</Grid>
</GroupBox>
完整代码请参见此处:https://github.com/SciLor/MashedTrainer
答案 0 :(得分:1)
在WPF中复制控制树不是一个好方法。
你应该坚持MVVM范式, 定义数据的视图模型类,并使用数据模板,样式和数据绑定来构建视图。
所以你应该有一个玩家类的数据模板,它将作为一个视图,知道如何显示播放器,并使用数据绑定绑定到玩家的属性。
当您将一个播放器或一组播放器放入列表控件中作为其内容属性时,wpf将能够全部呈现它们。
网络上有很多关于此主题的资源,对于初学者,您可以查看this simple MVVM example和data binding overview。