如何将滑块值链接到文本块的FontSize,并将该值存储在ApplicationData变量中

本文关键字:存储 ApplicationData 变量 链接 文本 FontSize | 更新日期: 2023-09-27 18:07:34

我希望你能帮我解决我的问题。我有一个简单的地铁应用程序。一个名为myTextBlock的文本块被放置在HomePageView页面。这是xaml:

<TextBlock x:Name="myTextBlock" Text="Hello" HorizontalAlignment="Center" VerticalAlignment="Top" Style="{StaticResource timeStyle}" TextAlignment="Center" FontSize="300"  RenderTransformOrigin="0.5,0.5" Margin="11,55,3,0"  ManipulationMode="All">

这是homeepageview代码后面的LoadState:

 protected override void LoadState(Object navigationParameter, Dictionary<String, Object> pageState)
        {
            try
            {
                double? myTextBlockValue = (double?)ApplicationData.Current.LocalSettings.Values["myTextBlockSize"];
                if (myTextBlockValue != null)
                {
                    myTextBlock.FontSize = (double)myTextBlockValue;
                }
            }
            catch
            {
            }
        }

我构建了一个名为settingpage的设置窗格(魅力栏->设置->设置),其中放置了一个名为timeSlider的滑块。这是xaml:

<Slider x:Name="timeSlider" Width="257" Minimum="1" Maximum="600" Loaded="timeSlider_Loaded" ValueChanged="timeSlider_ValueChanged" />

这些是放置在settingpage代码后面的slider Loaded和ValueChanged方法

 private void timeSlider_Loaded(object sender, RoutedEventArgs e)
        {
            var sliderIstance = sender as Slider;
            double? storedSize = (double?)ApplicationData.Current.LocalSettings.Values["myTextBlockSize"];
            if (storedSize != null && storedSize != 1)
                sliderIstance.Value = (double)storedSize;
            else
                sliderIstance.Value = 300;
        }
        private void timeSlider_ValueChanged(object sender, RangeBaseValueChangedEventArgs e)
        {
            var sliderIstance = sender as Slider;
            ApplicationData.Current.LocalSettings.Values["myTextBlockSize"] = sliderIstance.Value as double?;
            var _Frame = Window.Current.Content as Frame;
            _Frame.Navigate(_Frame.Content.GetType());
            _Frame.GoBack();
        }

你可以在我的skydrive下载完整的解决方案:https://skydrive.live.com/redir?resid=1B721133DC03E67C!7350

通过这种方式,我将myTextBlock的fontsize属性(在HomePageView页面中)链接到滑动条的value属性(在settingpage页面中),因此用户可以在运行时更改该属性。此外,该属性存储在myTextBlockSize ApplicationData变量中,以便在应用程序关闭和重新打开时保留其值。

解决方案是有效的,但问题是:当我进入设置窗格(魅力栏->设置->设置),并通过滑块改变textblock字体大小属性,然后我回到主页视图,重新打开设置窗格,字体大小属性被重新初始化为其原始值,所以它不会保持以前的(用户选择)值。你能修改我的代码吗?非常感谢。

如何将滑块值链接到文本块的FontSize,并将该值存储在ApplicationData变量中

您必须在timeSlider_ValueChanged事件中添加一个条件if (sliderIstance.Value != 1)

private void timeSlider_ValueChanged(object sender, RangeBaseValueChangedEventArgs e)
{
    var sliderIstance = sender as Slider;
    if (sliderIstance.Value != 1)
        ApplicationData.Current.LocalSettings.Values["myTextBlockSize"] = sliderIstance.Value as double?;
    var _Frame = Window.Current.Content as Frame;
    _Frame.Navigate(_Frame.Content.GetType());
    _Frame.GoBack();
}