我正在創建一個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