I am trying to create a converter that will take string property from ViewModel, compare it to time passed (time is inputted to TextBox HoursLimitProp in a format 07:30) and then change Label color accordingly. I know this is bad idea to do this way with
var SVM = new SettingsViewModel();
So what is the right way of accessing property in ViewModel from IValueConverter? I have tried to change SVM.HoursLimitProp to text as it is actually a value, but then I am getting null exception.
TimeExceededConverter.cs:
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Windows.Data;
using System.Windows.Media;
namespace Activitytracker
{
class TimeExceededConverter : IValueConverter
{
#region IValueConverter Members
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
string text = (string)value;
var dateNow = DateTime.Now;
var SVM = new SettingsViewModel();
List<int> TimeSplit = SVM.HoursLimitProp.Split(':').Where(x => int.TryParse(x, out _)).Select(int.Parse).ToList();
DateTime RingTime = new DateTime(dateNow.Year, dateNow.Month, dateNow.Day, TimeSplit[0], TimeSplit[1], 00);
TimeSpan res;
var result = TimeSpan.TryParseExact(text, @"hh\:mm\:ss", CultureInfo.InvariantCulture, out res);
if (res < RingTime.TimeOfDay)
{
return Brushes.Green;
}
return Brushes.Red;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
return Binding.DoNothing;
}
#endregion
}
}
SettingsViewModel.cs:
....
private string _hoursLimit;
public string HoursLimitProp
{
get { return _hoursLimit; }
set
{
if (_hoursLimit != value)
{
_hoursLimit = value;
OnPropertyChanged();
}
}
}
....
MainWindow.xaml:
...
<Label DataContext="{Binding ViewModel}" Style="{StaticResource TopBarLabel_Style}" x:Name="lblTime"
Content="{Binding Path=CurrentTime}" HorizontalAlignment="Left" Height="33"
Foreground="{Binding Path=CurrentTime, Converter={StaticResource TimeExceededConverter}}"
Width="89" Grid.Column="1"/>
...