如何在TextBlock MVVM Light中突出显示日期 [英] How to highlight dates in a TextBlock MVVM Light
问题描述
我想根据当前日期突出显示日期的前景色或背景色.如何在ViewModel中做到这一点?
I want to highlight the foreground or background color of the dates based on current date. How can I do it in my ViewModel?
我可以用来突出显示日期的代码是什么?
What are the codes I can use to highlight the date?
这是我整个项目的代码:
Here are my codes for the whole project:
xaml:
<Grid Margin="10,102,10,298">
<GridView ItemsSource="{Binding Calendar.DateCollection}">
<GridView.ItemTemplate>
<DataTemplate>
<Grid x:Name="dateGrid" Background="AntiqueWhite" Width="50" Height="30">
<TextBlock x:Name="txtDate" Text="{Binding}" Foreground="Black" VerticalAlignment="Center" HorizontalAlignment="Center" IsTapEnabled="True"/>
</Grid>
</DataTemplate>
</GridView.ItemTemplate>
</GridView>
</Grid>
完整的ViewModel:
Complete ViewModel:
DateTime calendarDate;
public calendarViewModel()
{
calendarDate = DateTime.Today;
Initialize_Calendar(calendarDate);
}
private ObservableCollection<string> _DATECollection = new ObservableCollection<string>();
public ObservableCollection<string> DateCollection
{
get
{
return _DATECollection;
}
set
{
_DATECollection = value;
}
}
private ObservableCollection<Event> _eventCollection = new ObservableCollection<Event>();
public ObservableCollection<Event> EventCollection
{
get
{
return _eventCollection;
}
set
{
_eventCollection = value;
}
}
/// <summary>
/// The <see cref="CalendarMonthYear" /> property's name.
/// </summary>
public const string CalendarMonthYearPropertyName = "CalendarMonthYear";
private string _calendarMonthYear ;
/// <summary>
/// Sets and gets the CalendarMonthYear property.
/// Changes to that property's value raise the PropertyChanged event.
/// </summary>
public string CalendarMonthYear
{
get
{
return _calendarMonthYear;
}
set
{
if (_calendarMonthYear == value)
{
return;
}
_calendarMonthYear = value;
RaisePropertyChanged(CalendarMonthYearPropertyName);
}
}
//button next month
private RelayCommand _nextMonth;
/// <summary>
/// Gets the NextMonth.
/// </summary>
public RelayCommand NextMonth
{
get
{
return _nextMonth
?? (_nextMonth = new RelayCommand(
() =>
{
calendarDate = calendarDate.AddMonths(1);
Initialize_Calendar(calendarDate);
}));
}
}
//Button previous month
private RelayCommand _previousMonth;
/// <summary>
/// Gets the PreviousMonth.
/// </summary>
public RelayCommand PreviousMonth
{
get
{
return _previousMonth
?? (_previousMonth = new RelayCommand(
() =>
{
calendarDate = calendarDate.AddMonths(-1);
Initialize_Calendar(calendarDate);
}));
}
}
/// <summary>
/// The <see cref="DATE" /> property's name.
/// </summary>
public const string DATEPropertyName = "DATE";
private string _date;
/// <summary>
/// Sets and gets the DATE property.
/// Changes to that property's value raise the PropertyChanged event.
/// </summary>
public string DATE
{
get
{
return _date;
}
set
{
if (_date == value)
{
return;
}
_date = value;
RaisePropertyChanged(DATEPropertyName);
}
}
public void Initialize_Calendar(DateTime date)
{
CalendarMonthYear = date.ToString("MMMM yyyy");
date = new DateTime(date.Year, date.Month, 1);
int dayOfWeek = (int)date.DayOfWeek + 1;
int daysOfMonth = DateTime.DaysInMonth(date.Year, date.Month);
int i = 1;
DateCollection.Clear();
for (int d = 1; d <= daysOfMonth; d++ )
{
if (i >= dayOfWeek && i < (daysOfMonth + dayOfWeek))
{
DATE = (i - dayOfWeek + 1).ToString();
DateCollection.Add(DATE);
}
else
{
DATE = "";
DateCollection.Add(DATE);
if (DATE == "")
{
daysOfMonth++;
}
}
i++;
}
}
private RelayCommand _dateClick;
/// <summary>
/// Gets the DateClick.
/// </summary>
public RelayCommand DateClick
{
get
{
return _dateClick
?? (_dateClick = new RelayCommand(
async() =>
{
EventCollection.Clear();
List<Event> E = await App.MobileService.GetTable<Event>().ToListAsync();
foreach(Event evnt in E)
{
if (evnt.Date.Date.Equals(DateTime.Today.Date))
{
EventCollection.Add(new Event
{
Id = evnt.Id,
EventName = evnt.EventName,
Desc = evnt.Desc,
Category = evnt.Category,
Location = evnt.Location,
StartingTime = evnt.StartingTime,
Date = evnt.Date
});
}
}
if(EventCollection.Count == 0 )
{
MessageDialog m = new MessageDialog("Empty", "No Events today!.");
await m.ShowAsync();
}
}));
}
}
DateConverter类别:
DateConverter Class:
public class DateColorConvertor : IValueConverter
{
public object ConvertBack(object value, Type targetType, object parameter,
System.Globalization.CultureInfo culture)
{
return new object();
}
public object Convert(object sender, Type targetType, object parameter, string language)
{
DateTime currentItem = DateTime.Parse((sender as TextBlock).Text);
if (currentItem == DateTime.Now)
return new SolidColorBrush(Colors.Green);
else
return new SolidColorBrush(Colors.Red);
//throw new NotImplementedException();
}
public object ConvertBack(object value, Type targetType, object parameter, string language)
{
throw new NotImplementedException();
}
}
推荐答案
您应该使用转换器来执行此操作,这涉及以下步骤
You should use a converter to do that, this involves the following steps
1) create the converter class, it should implement the IValueConverter
2)实现Convert
方法,据我了解您想基于当前日期执行此操作,因此应该像
2) Implement the Convert
method, as I understand you want to do this based on current date so it should be like
///假设您项目中的日期是可解析的格式
//supposing that the date in your item is an a parseable format
DateTime currentItem = DateTime.Parse((sender as TextBlock).Text)
if(currentItem == DateTime.Now) // your comparison goes here
return new SolidColorBrush(Colors.Green);
else
return new SolidColorBrush(Colors.Red);
下一步,请在您的XAML代码中声明名称空间
Next step declare the namespace in your XAML Code
xmlns:src="clr-namespace:PhoneApp1" // src is the name, PhoneApp1 the namespace
然后在网格中将其添加到资源中
Then in the Grid add it in the resources
<Grid.Resources>
<src:DateColorConverter x:Key="DateColorConverter" />
</Grid.Resources>
最后在您的Textblock中将ForeGround设置为
Finally in your Textblock set the ForeGround to
Foreground="{Binding Converter={StaticResource DateColorConverter}}"
基本上,这里要做的是将要绑定到列表中的每个对象进行检查,并在运行时获取值.
What is essentially done here is that every object the will be binded in your lists, goes through a check and gets the value on the runtime.
您还可以尝试检查此示例,这是希腊文,但是通过Google翻译,您会了解它的工作原理.
You can also try checking this example, it's in greek but with some google translate you'll understand how it works.
这篇关于如何在TextBlock MVVM Light中突出显示日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!