c# - 使用 XAML 和 C# 为 Windows Phone 8 应用构建自定义进度条

标签 c# wpf xaml windows-phone-8

我正在尝试制作一个随时间减少的条。

使用的xaml是

     <Grid x:Name="LayoutRoot" Background="Transparent">
      <TextBlock  Text="Timer :-" FontSize="35" Width="120" Height="70" Margin="138,167,222,531" ></TextBlock>
    <TextBlock x:Name="clock" FontSize="35" Width="100" Height="70" Margin="259,169,121,529" ></TextBlock>

    <Image x:Name="bar" Width="350" Height="20" Source="Assets/progress_bar_bg.png" Margin="65,271,65,477" ></Image>
    <Image x:Name="gbar"  Width="350" Height="20" Source="Assets/green_progress_bar.png" Margin="65,271,65,477" ></Image>

</Grid>

我的c#代码是

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Net;
    using System.Windows;
    using System.Windows.Controls;
    using System.Windows.Navigation;
    using Microsoft.Phone.Controls;
    using System.Windows.Threading;
    using Microsoft.Phone.Shell;

    namespace PhoneApp1
    {
        public partial class ProgressBar : PhoneApplicationPage
        {
    public ProgressBar()
    {
        InitializeComponent();

        newTimer.Interval = TimeSpan.FromSeconds(1);
        newTimer.Tick += OnTimerTick;
        newTimer.Start();
        clock.Text = " 00:60";
    }

    DispatcherTimer newTimer = new DispatcherTimer();
    int counter = 60;

    int width = 350;
    double i=5.8;

    void OnTimerTick(Object sender, EventArgs args)
    {
        counter--;

        if (counter < 0)
        {
            newTimer.Stop();
            counter = 60;
        }
        else
        {


                gbar.Width = width - i;

                clock.Text = " 00:" + counter.ToString();
                i=i+5.8;

            }
        }
    }
}

我已经减小了宽度,这样图像 green_progress_bar.png 的大小应该减小但问题是它从两端减小我希望它应该随着时间从 60 秒减少到 0 从右到左减小秒。而且高度也随着时间的推移而降低,我希望图像高度是固定的。

这是我的案例中发生的事情的图像。

enter image description here

enter image description here

enter image description here

我希望条形的宽度应该从右到左减小。但它从两端都在减小。 请帮帮我。

提前致谢。

最佳答案

好的 - 这将是一篇很长的文章。所以首先 - 结果:

ProgressTimer

我对您的代码进行了很多更改(IMO,有些事情可能会得到改进)。首先 - Slider 的样式(我已经删除了大部分您不需要的东西。您可以在 MSDN 或使用 Blend 找到完整的模板):

<phone:PhoneApplicationPage.Resources>
    <Style x:Key="SliderStyle1" TargetType="Slider">
        <Setter Property="BorderThickness" Value="0"/>
        <Setter Property="BorderBrush" Value="Transparent"/>
        <Setter Property="Maximum" Value="10"/>
        <Setter Property="Minimum" Value="0"/>
        <Setter Property="Value" Value="0"/>
        <Setter Property="Background" Value="{StaticResource PhoneChromeBrush}"/>
        <Setter Property="Foreground" Value="{StaticResource PhoneAccentBrush}"/>
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="Slider">
                    <Grid Background="Transparent">
                        <Grid x:Name="HorizontalTemplate" Margin="{StaticResource PhoneHorizontalMargin}">
                            <Rectangle x:Name="HorizontalTrack" Fill="{TemplateBinding Background}" Height="12" IsHitTestVisible="False" Margin="0,22,0,50"/>
                            <Rectangle x:Name="HorizontalFill" Fill="GreenYellow" Height="12" IsHitTestVisible="False" Margin="0,22,0,50">
                                <Rectangle.Clip>
                                    <RectangleGeometry Rect="0, 0, 6, 12"/>
                                </Rectangle.Clip>
                            </Rectangle>
                            <Ellipse x:Name="HorizontalCenterElement" HorizontalAlignment="Left" Height="12" Margin="0,16,0,44" Width="12" Fill="GreenYellow">
                                <Ellipse.RenderTransform>
                                    <TranslateTransform/>
                                </Ellipse.RenderTransform>
                            </Ellipse>
                        </Grid>                            
                    </Grid>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
    </Style>
</phone:PhoneApplicationPage.Resources>

上面代码中最重要的是:Horizo​​ntalTrackHorizo​​ntalFillHorizo​​ntalCenterElement - 您可以更改颜色、形状等.我已将 centerelement 设置为椭圆形,因此它在末尾有点圆润。最好的情况是你只是玩它。使用样式是这样的:

<Grid x:Name="LayoutRoot" Background="Transparent">
    <Grid.RowDefinitions>
        <RowDefinition Height="Auto"/>
        <RowDefinition Height="*"/>
    </Grid.RowDefinitions>

    <Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">
        <Grid.RowDefinitions>
            <RowDefinition Height="1*"/>
            <RowDefinition Height="1*"/>
            <RowDefinition Height="2*"/>
            <RowDefinition Height="6*"/>
        </Grid.RowDefinitions>
        <Button x:Name="buttonStart" VerticalAlignment="Top" Content="Start" Grid.Row="0"/>
        <TextBlock Name="clock" HorizontalAlignment="Center" VerticalAlignment="Center" Text="{Binding ClockText}" Grid.Row="1"/>
        <Slider Name="gbar" VerticalAlignment="Center" Orientation="Horizontal" HorizontalAlignment="Stretch" 
                Grid.Row="2" Style="{StaticResource SliderStyle1}" IsHitTestVisible="False"
                Value="{Binding ValueLeft, Mode=TwoWay}" Maximum="{Binding MaxValue}"/>

    </Grid>
</Grid>

一些事情:

  • 我已经更改了 UIElements 的内容并将它们绑定(bind)到实现 INotifyPropertyChanged 的​​属性
  • 我已禁用 Slider 以进行 HitTest - 因此用户将无法通过触摸来更改它

后面的其余代码:

public partial class MainPage : PhoneApplicationPage, INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;

    public void RaiseProperty(string property = null)
    { if (this.PropertyChanged != null)                this.PropertyChanged(this, new PropertyChangedEventArgs(property)); }

    private TimeSpan timeLeft = TimeSpan.FromSeconds(60);
    public TimeSpan TimeLeft
    {
        get { return timeLeft; }
        set
        {
            timeLeft = value;
            RaiseProperty("ClockText");
            RaiseProperty("ValueLeft");
        }
    }

    public string ClockText { get { return timeLeft.ToString("m\\:ss"); } }

    public double ValueLeft { get { return TimeLeft.Ticks; } }

    private double maxValue = TimeSpan.FromSeconds(60).Ticks;
    public double MaxValue // number of seconds
    {
        get { return maxValue; }
        set
        {
            TimeLeft = TimeSpan.FromSeconds(value);
            maxValue = TimeLeft.Ticks;
            RaiseProperty("MaxValue");
        }
    }

    System.Threading.Timer newTimer;
    private bool timerStarted = false;

    public MainPage()
    {
        InitializeComponent();
        this.DataContext = this;
        newTimer = new Timer(OnTimerTick);
        buttonStart.Click += buttonStart_Click;
    }

    private void buttonStart_Click(object sender, RoutedEventArgs e)
    {
        if (!timerStarted)
        {
            buttonStart.Content = "STOP";
            MaxValue = 60;
            timerStarted = true;
            newTimer.Change(TimeSpan.FromSeconds(0), TimeSpan.FromSeconds(1)); // start timer right now and invoke every second
        }
        else
        {
            buttonStart.Content = "Start";
            timerStarted = false;
            newTimer.Change(0, Timeout.Infinite); // stop the timer
        }
    }

    void OnTimerTick(object state)
    { Dispatcher.BeginInvoke(() => TimeLeft -= TimeSpan.FromSeconds(1)); }
}

这里有几件事:

  • 我已经组织了属性,现在当我更改 TimeLeft 时,TextBlock 和 Slider 会更新 - 绑定(bind)
  • 我已将您的 DispatcherTimer 更改为 System.Threading.Timer - 它在单独的线程上运行,因此不会阻塞 UI(当会有更多计算时)
  • 由于该单独的线程,回调内部(在 UI 上)的更改必须通过 Dispatcher 进行。

当间隔为 1 秒时,此示例肯定会与 DispatcherTimer 一起正常工作,但如果您计划执行更多计算,第二个 Timer 可能是更好的选择。 (这只是一种不同的可能性)。

关于c# - 使用 XAML 和 C# 为 Windows Phone 8 应用构建自定义进度条,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23109995/

相关文章:

C#非UI跨线程调用

c# - 将代码与空格对齐时阻止 IDE0055 样式分析器

wpf - Bing WPF map 控件图钉颜色

c# - 将数据从代码隐藏到 XAML 的简单绑定(bind)

WPF 绑定(bind)渲染 Gui 进度

silverlight - 如何在 Windows Phone 8 上将数据与常量字符串绑定(bind)

c# - 用于检查文件内容类型的正则表达式是否为 .doc?

c# - Docx内容替换

c# - 将 xaml 代码移至 View 模型类

c# - 相对于元素存储数据字符串的最佳方式