我们需要在 UWP 应用程序中为相同的 .cs 创建 4 个不同的 .xaml 布局。这些布局的结构取决于来自 db 的值“questionType”。
布局的每个变体都应包含相同的控件但位置不同。(即每个变体应包含一个图像、一个 richTextEditor 和包含 4 个 radio 的 radioGroup)
例如,如果 questionType=1,图像应该位于屏幕的左侧,如果 questionType=2,那么它应该位于富文本编辑器的顶部, radio 也应该水平放置...
我们已经考虑和尝试过的事情:
到目前为止,我们已经尝试过可视化状态管理器,但不幸的是,使用它我们只能更改控件的对齐方式,而不能更改控件的位置。
我们还检查了条件 xaml,但它似乎只是为了版本适应性。
可见性不断变化的面板。但我们决定不采用这种解决方案,因为它非常丑陋。
任何能为我们指明正确方向的人,我们都将不胜感激。
谢谢。
编辑:
<VisualState x:Name="Layout1">
<Storyboard>
<ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="(FrameworkElement.HorizontalAlignment)"
Storyboard.TargetName="ContentRoot">
...
</ObjectAnimationUsingKeyFrames>
</Storyboard>
</VisualState>
最佳答案
VisualStateManager 可以更改您在元素上定义的任何属性,而不仅仅是对齐方式。
为了简单起见,我用两个Border
分别代表Image
和RichTextBox
。最初图像位于左侧,然后我使用 VisualStateManager
转到另一个视觉状态,其中 Image
位于顶部。请注意,属性 (Grid.Column)
和 (Grid.Row)
的更改就像 (FrameworkElement.HorizontalAlignment)
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="*" />
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<Border x:Name="imageControl"
Background="Red"
Height="200" Width="200"
Grid.Row="1" />
<Border x:Name="richTextBoxControl"
Background="Green"
HorizontalAlignment="Stretch"
VerticalAlignment="Stretch"
Grid.Row="1" Grid.Column="1" />
<VisualStateManager.VisualStateGroups>
<VisualStateGroup>
<VisualState x:Name="Layout1" />
<VisualState x:Name="Layout2">
<Storyboard>
<ObjectAnimationUsingKeyFrames
Storyboard.TargetName="imageControl"
Storyboard.TargetProperty="(Grid.Column)">
<DiscreteObjectKeyFrame KeyTime="0" Value="1" />
</ObjectAnimationUsingKeyFrames>
<ObjectAnimationUsingKeyFrames
Storyboard.TargetName="imageControl"
Storyboard.TargetProperty="(Grid.Row)">
<DiscreteObjectKeyFrame KeyTime="0" Value="0" />
</ObjectAnimationUsingKeyFrames>
</Storyboard>
</VisualState>
</VisualStateGroup>
</VisualStateManager.VisualStateGroups>
</Grid>
在代码隐藏中,根据值 questionType
更改 VisualState
。
if (questionType == 1)
return; //Layout1 is the default state
else if (questionType == 2)
VisualStateManager.GoToState(this, "Layout2", true);
还有其他方法,例如使用 StackPanel 来承载控件,最初是水平方向的,然后在其他视觉状态下将其更改为垂直方向。
关于c# - UWP 中一个 CS 文件的不同 XAML 布局结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53301290/