我想知道是否可以在单独的。xaml文件(与主页分离),但这当然需要在主页内运行。
实现此功能的最佳实践是
UserControl
. 你可以创造
VisualStateGroup
在您的
用户控件
.
<Grid x:Name="RootLayout" Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
<VisualStateManager.VisualStateGroups>
<VisualStateGroup x:Name="AdaptiveVisualStateGroup">
<VisualState x:Name="VisualStateNarrow">
<VisualState.StateTriggers>
<AdaptiveTrigger MinWindowWidth="{StaticResource NarrowMinWidth}" />
</VisualState.StateTriggers>
<VisualState.Setters>
<Setter Target="RootLayout.Background" Value="Red" />
</VisualState.Setters>
</VisualState>
<VisualState x:Name="VisualStateNormal">
<VisualState.StateTriggers>
<AdaptiveTrigger MinWindowWidth="{StaticResource NormalMinWidth}" />
</VisualState.StateTriggers>
<VisualState.Setters>
<Setter Target="RootLayout.Background" Value="Blue" />
</VisualState.Setters>
</VisualState>
<VisualState x:Name="VisualStateWide">
<VisualState.StateTriggers>
<AdaptiveTrigger MinWindowWidth="{StaticResource WideMinWidth}" />
</VisualState.StateTriggers>
<VisualState.Setters>
<Setter Target="RootLayout.Background" Value="Green" />
</VisualState.Setters>
</VisualState>
</VisualStateGroup>
</VisualStateManager.VisualStateGroups>
<ContentPresenter Grid.Row="1" Content="{x:Bind Main}" />
</Grid>
在代码隐藏中,设置
DependencyProperty
以便我们可以使用它们设置其他页面中的内容。
public sealed partial class PageUserControl : UserControl
{
public PageUserControl()
{
this.InitializeComponent();
}
public static readonly DependencyProperty MainProperty = DependencyProperty.Register("Main", typeof(object), typeof(PageUserControl), new PropertyMetadata(null));
public object Main
{
get { return GetValue(MainProperty); }
set { SetValue(MainProperty, value); }
}
}
在主页中使用它
<Page
x:Class="Test.MainPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:Test"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d">
<local:PageUserControl>
<local:PageUserControl.Main>
<Grid>
<TextBlock HorizontalAlignment="Center" VerticalAlignment="Center" FontSize="60" Text="Hello"></TextBlock>
</Grid>
</local:PageUserControl.Main>
</local:PageUserControl>
</Page>