我想要导航到我的Windows Phone 8.1应用程序中的另一个页面。如果有一个按钮,只需点击它并使用Frame.Navigate(typeof(MainPage));
中的event handler
即可轻松完成此操作。但在我的情况下我想根据整数值自动导航到第二页。如果它变为零,页面会自动转到第二页。在我的情况下,我没有button
所以event handler
这样做这个。我怎么能这样做?
答案 0 :(得分:2)
为您的视图模型实现INotifyPropertyChanged接口。这是一个粗略的实现,理想情况下,您将使用mvvm框架并根据需要向您的视图发送消息。
查看模型
public class GameStateViewModel : INotifyPropertyChanged
{
private int currentScore = 10;
/// <summary>
/// The timer here added to simulate whatever is supposed to be changing your value.
/// </summary>
public GameStateViewModel()
{
var timer = new DispatcherTimer
{
Interval = TimeSpan.FromSeconds(2)
};
timer.Tick += (sender, args) =>
{
if (this.CurrentScore > 0)
{
this.CurrentScore--;
}
else
{
timer.Stop();
}
};
timer.Start();
}
public event PropertyChangedEventHandler PropertyChanged;
public int CurrentScore
{
get { return currentScore; }
set
{
currentScore = value;
NotifyPropertyChanged("CurrentScore");
}
}
public void NotifyPropertyChanged(string propertyName)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
}
背后的代码
public partial class MainPage : PhoneApplicationPage
{
// Constructor
public MainPage()
{
InitializeComponent();
var viewModel = new GameStateViewModel();
viewModel.PropertyChanged += (sender, args) =>
{
if (viewModel.CurrentScore <= 0)
{
this.NavigationService.Navigate(new Uri("/Page2.xaml", UriKind.Relative));
}
};
this.DataContext = viewModel;
}
}
的Xaml
<Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">
<TextBlock Text="{Binding CurrentScore}" FontSize="{StaticResource PhoneFontSizeExtraLarge}" />
</Grid>