我正在创建一个Windows通用应用程序(WinRT和WP8.1)。 我想要的是让用户在同一页面的两种不同布局之间进行选择。 以下是简单表示。 我想找到最简单,最懒惰的方法(我知道我可以创建两个页面,但必须有更好的方法。) 我已经创建了1页(后面有500行C#代码来处理控件交互)现在需要添加第二个布局。这两个布局具有完全相同的功能,并且控件具有相同的名称,它们的排列方式不同。背后有两个相同代码的XAML页面
在Android中我可以这样做:
if(IsLayout1Selected)
setContentView(R.layout.activity_d2p_layout1);
else
setContentView(R.layout.activity_d2p_layout2);
预先感谢您的帮助!
布局1:
<Page x:Name="d2pPageLayout1"
x:Class="_MyApp.D2P"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:_MyApp"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d" Unloaded="PageUnloaded" Loaded="PageLoaded"
Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
<Grid x:Name="mainGrid">
<Button x:Name="button1" VerticalAlignment="Top" Click="buttonClick"/>
<TextBlock x:Name="textblock1" Text="Hello"/>
<!-- Of course there are a lot more elements and they have many layout properties that differ -->
</Grid>
</Page>
布局2:
<Page x:Name="d2pPageLayout2"
x:Class="_MyApp.D2P"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:_MyApp"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d" Unloaded="PageUnloaded" Loaded="PageLoaded"
Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
<Grid x:Name="mainGrid">
<Button x:Name="button1" VerticalAlignment="Bottom" Click="buttonClick"/>
<TextBlock x:Name="textblock1" Text="Hello"/>
<!-- Of course there are a lot more elements and they have many layout properties that differ -->
</Grid>
</Page>
代码后面(对于相同布局1和布局2):
namespace _MyApp
{
public sealed partial class D2P : Page
{
public D2P()
{
this.InitializeComponent();
}
private void PageLoaded(object sender, RoutedEventArgs e)
{
// do stuff here
}
private void PageUnloaded(object sender, RoutedEventArgs e)
{
// do some other stuff here
}
private void buttonClick(object sender, RoutedEventArgs e)
{
// handle buttonClick here
// a lot of this code also references the controls directly e.g.
textblock1.Text = "Button 1 was clicked";
}
}
}
编辑:
感谢来自阿克沙伊SOAM尖端我就非常接近我想要的东西用的DataTemplate和ContentControl中,但现在这会导致另一个问题,打破我的代码。我的代码直接访问很多元素。 例子:
textblock1.Text = "Button 1 was clicked";
因为我的整个页面的内容现在包裹的DataTemplate内无法访问的元素了。我该怎么做呢?
当前实现:
XAML:
<Page.Resources>
<DataTemplate x:Key="template1">
<Button x:Name="button1" VerticalAlignment="Bottom" Click="buttonClick"/>
<TextBlock x:Name="textblock1" Text="Hello"/>
</DataTemplate>
</Page.Resources>
<ContentControl x:Name="contentControl" Content="{Binding}"/>
后面的代码:
contentControl.ContentTemplate = template1;
this.DataContext = template1;
你可以使用一个内容控件和一个数据模板 – thumbmunkeys 2014-10-18 12:21:56
@thumbmunkeys谢谢,这让我有一半在那里,我已经更新了问题与一个由此产生的问题。 – Johis 2014-10-18 19:00:08