我什至不知道我是否在代码隐藏中使用了“正确”的方法,但 MVVM 似乎没有用,因为这不是 CRUD 应用程序(没有用户输入的简单信息.)
不,MVVM 很有用,在 MVVM 设计模式中,开发人员可以编写应用程序逻辑,而设计人员可以创建 UI。尽管您不是在开发 CRUD 应用程序,但仍然可以使用 MVVM 模式。
在 UWP 应用中,Data Binding 非常强大。在这种情况下,您可以使用数据绑定和Converter 一起解决您的问题。
我这里写了一个示例,使用Data Binding进行事件,并使用Converter判断Button和AppBarButtons的Visibility:
<Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
<Grid.Resources>
<Converter:VisiableOrNot x:Key="cvt" />
<Converter:NaviButtonShowOrNot x:Key="btncvt" />
</Grid.Resources>
<CommandBar>
<CommandBar.Content>
<Grid>
<TextBlock Text="Master-Frame" FontSize="20" Margin="20,10" />
</Grid>
</CommandBar.Content>
<AppBarButton Icon="Accept" Label="appbarbutton" Visibility="{Binding ElementName=mainPageframe, Path=Content.BaseUri.AbsoluteUri, Converter={StaticResource cvt}}" />
<AppBarButton Icon="Cancel" Label="appbarbutton" Visibility="{Binding ElementName=mainPageframe, Path=Content.BaseUri.AbsoluteUri, Converter={StaticResource cvt}}" />
</CommandBar>
<Frame x:Name="mainPageframe" Margin="0,55">
<Hub x:Name="hub" SectionHeaderClick="{x:Bind MainPageViewModel.hub_SectionHeaderClick}">
<HubSection x:Name="image1" Header="Image1" Width="200" IsHeaderInteractive="True">
<DataTemplate>
<Grid>
<Image Source="Assets/111.png" Stretch="None" />
</Grid>
</DataTemplate>
</HubSection>
<HubSection x:Name="image2" Header="Image2" Width="200" IsHeaderInteractive="True">
<DataTemplate>
<Grid>
<Image Grid.Row="0" Source="Assets/222.png" Stretch="None" />
</Grid>
</DataTemplate>
</HubSection>
<HubSection x:Name="image3" Header="Image3" Width="200" IsHeaderInteractive="True">
<DataTemplate>
<Grid>
<Image Source="Assets/333.png" Stretch="None" />
</Grid>
</DataTemplate>
</HubSection>
</Hub>
</Frame>
<Button Content="Go Back" Click="{x:Bind MainPageViewModel.Button_Click}" Background="PaleGreen" VerticalAlignment="Bottom" Margin="50,20" Visibility="{Binding ElementName=mainPageframe, Path=Content.BaseUri.AbsoluteUri, Converter={StaticResource btncvt}}" />
</Grid>
VisiableOrNot转换器的代码:
public class VisiableOrNot : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, string language)
{
Uri uri = new Uri(value.ToString());
if (uri != null)
{
if (uri.Equals("ms-appx:///View/Page3.xaml"))
{
return Visibility.Visible;
}
}
return Visibility.Collapsed;
}
public object ConvertBack(object value, Type targetType, object parameter, string language)
{
throw new NotImplementedException();
}
}
这是我demo的渲染图,AppBarButtons只有在子框架的内容为Page3时才能看到。并且导航返回按钮在 MainPage 上时看不到:
这是我的demo,你可以下载看看。