我失去了一些東西在這裏真的很明顯,但只是不能做出來:(依賴項屬性恢復導航
我有一個2頁Windows應用商店的應用程序與Dependency Property
稱爲秒。 如果你點擊之後恢復爲默認值啓動按鈕,計時器將開始和Seconds
價值將隨着預期的 但如果我瀏覽到Page2
,然後再返回到MainPage
的DP復位在UI爲默認值,儘管實際值是正確的。
我可以看到這通過在_timer.tick事件上放置一個斷點來實現DP未處於其默認值,但隨着計時器仍在運行而降低。我想這反映在UI 任何幫助表示讚賞?
MainPage.xaml中
<Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="1*"/>
<ColumnDefinition Width="1*"/>
</Grid.ColumnDefinitions>
<StackPanel>
<Button x:Name="btnNav" Content="Page 2" Width="150" Height="60" Click="btnNav_Click"></Button>
<Button x:Name="btnStart" Content="Start" Width="150" Height="60" Click="btnStart_Click"></Button>
</StackPanel>
<StackPanel Grid.Column="1">
<TextBlock x:Name="txtSeconds" FontSize="25" Text="{Binding Path=Seconds}" />
</StackPanel>
</Grid>
MainPage.cs
public sealed partial class MainPage : Page
{
private static DispatcherTimer _timer;
public MainPage()
{
this.InitializeComponent();
Loaded += (s, args) =>
{
if (_timer == null)
{
_timer = new DispatcherTimer();
_timer.Interval = TimeSpan.FromMilliseconds(1000);
_timer.Tick += (sender, e) =>
{
Seconds--;
};
}
this.DataContext = this;
};
}
public int Seconds
{
get { return (int)GetValue(SecondsProperty); }
set { SetValue(SecondsProperty, value); }
}
// Using a DependencyProperty as the backing store for Seconds. This enables animation, styling, binding, etc...
public static readonly DependencyProperty SecondsProperty =
DependencyProperty.Register("Seconds", typeof(int), typeof(MainPage), new PropertyMetadata(100));
private void btnNav_Click(object sender, RoutedEventArgs e)
{
this.Frame.Navigate(typeof(Page2));
}
private void btnStart_Click(object sender, RoutedEventArgs e)
{
_timer.Start();
}
}
Page2.xaml
<Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
<AppBarButton Icon="Back" Click="AppBarButton_Click"></AppBarButton>
</Grid>
Page2.cs
public sealed partial class Page2 : Page
{
public Page2()
{
this.InitializeComponent();
}
private void AppBarButton_Click(object sender, RoutedEventArgs e)
{
this.Frame.Navigate(typeof(MainPage));
}
}
問題不是出在DP。當你回到同一頁面時,頁面被重新創建。您可以通過在MainPage構造函數上放置斷點來驗證。自從導航回主頁面後,您還沒有再次啓動計時器,因此GUI中沒有更新。 –
感謝您的回答。很抱歉忘記添加_timer是靜態的,所以仍然在返回頁面時運行並且打蜱事件正在被點擊 – SWilko