开发者

WPF: How to use a variable from code as property value in XAML?

I am implementing a countdown timer. I have a TextBlock which is showing the time, using DispatcherTimer.

I would like to create an animation for that TextBlock's FontSize property. I want its value to increase to 300pt at the point the timer shows 9pm. So, it starts with FontSize 8pt whenever the application is run and it keeps increasing and when the real time hits 9pm the FontSize should be 300pt.

Here's how I pictured it: Once the application is run, it will calculate the number of seconds it takes from that moment to get to 9pm; the result will be the stored by the variable timeToGetTo9pm. The problem I am facing is that when I create an animation in XAML, I don't know how to set timeToGetTo9pm to the animation Duration property.

Any ideas? Also, if my approach is stupid or confusing, please feel free to recommend a better one. Thanks.

Delegate body:

private void dispatcherTimer_Tick(object sender, EventArgs e)
{
    DateTime currentTime;
    double timeToNewYearInMiliseconds;

    currentTime = DateTime.Now;

    //targetTime is a DateTime object set elsewhere,开发者_如何学编程 
    //It represents the 9pm mentioned in the question body
    if (DateTime.Compare(targetTime, currentTime) > 0)
    {
        timeToNewYearInMiliseconds = targetTime.Subtract(currentTime).TotalMilliseconds;
        percent = 100 / timeToNewYearInMiliseconds;
        PercentageComplete = percent;
    }
}


Why not have a 'TimerFontSize' property in your ViewModel\Code-Behind and bind the TextBox's FontSize to it.

FontSize="{Binding TimerFontSize, Mode=OneWay}"

As your timer ticks, re-calculate the font size and set the 'TimerFontSize' property. If you have implemented INotifyPropertyChanged for 'TimerFontSize' the TextBox binding will automatically update and change the size of the font.

This pattern will use your timer, plus data-binding, to drive the animation.

Update

I see what you mean re. separating visual representation from data representation. My suggestion is the easy way. You could clean it up by making the exposed property an elapsed time or countdown value, and then use a ValueConverter to get a FontSize. This would separate data and view concepts.

Here's a code example of exposing a property in your code-behind. Simply use the binding I previously detailed to hook it up. Ideally you would refactor the code into a ViewModel class rather than have it in the code-behind, just taking things one step-at-a-time.

public partial class TimerView : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;
    private double _fontSize;
    private readonly DispatcherTimer _timer;

    public TimerView()
    {
        InitializeComponent();

        _timer = new DispatcherTimer { Interval = TimeSpan.FromSeconds(1) };
        _timer.Tick += delegate {/*calculate font size and set TimerFontSize*/};
        _timer.Start();
    }

    public double TimerFontSize
    {
        get { return _fontSize; }
        private set
        {
            _fontSize = value;
            InvokePropertyChanged("TimerFontSize");
        }
    }

    private void InvokePropertyChanged(string name)
    {
        if (PropertyChanged != null)
        {
            PropertyChanged(this, new PropertyChangedEventArgs(name));
        }
    }        
}

Update 2

And to separate model representation from view representation use a ValueConverter, e.g.:

Binding:

FontSize="{Binding PercentageComplete,
                   Mode=OneWay,
                   Converter={StaticResource percentToFontSizeConverter}}"

ValueConverter:

public class PercentToFontSizeValueConverter : IValueConverter
{
    private static double _DpiX;

    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        double percent = (double)value;
        double fontPointSize = (percent * 300);
        double fontDpiSize = (fontPointSize * (DpiX / 72d));
        return fontDpiSize;
    }

    private static double DpiX
    {
        get
        {
            if (_DpiX == 0)
            {
                Matrix m = PresentationSource.
                           FromVisual(Application.Current.MainWindow).
                           CompositionTarget.
                           TransformToDevice;

                _DpiX = (m.M11 * 96d);
            }

            return _DpiX;
        }
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        throw new NotImplementedException();
    }
}

Code-Behind:

public partial class TimerView : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;
    private double _percent;
    private readonly DispatcherTimer _timer;

    public TimerView()
    {
        InitializeComponent();

        _timer = new DispatcherTimer { Interval = TimeSpan.FromSeconds(1) };
        _timer.Tick += delegate{/*Calulate perecent and set PercentageComplete */};
        _timer.Start();
    }

    public double PercentageComplete
    {
        get { return _percent; }
        private set
        {
            _percent = value;
            InvokePropertyChanged("PercentageComplete");
        }
    }

    private void InvokePropertyChanged(string name)
    {
        if (PropertyChanged != null)
        {
            PropertyChanged(this, new PropertyChangedEventArgs(name));
        }
    }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜