【问题标题】:How to highlight dates in a TextBlock MVVM Light如何在 TextBlock MVVM Light 中突出显示日期
【发布时间】:2015-08-12 16:00:43
【问题描述】:

我想根据当前日期突出显示日期的前景色或背景色。我怎样才能在我的 ViewModel 中做到这一点?

我可以使用哪些代码来突出显示日期?

这是我整个项目的代码:

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:

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();
                        }
            }));
    }
}

日期转换器类:

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();
    }
}

【问题讨论】:

  • 文本框是否会包含除日期以外的文本,您是否只想突出显示日期?如果文本框包含多个日期会怎样? IE。 "今天是 8/12/2015,明天是 8/13/2015"
  • 它只是一个容器,它会在一个月内重复自己的日期。我想突出显示当前日期。

标签: c# windows-phone-8.1 mvvm-light


【解决方案1】:

你应该使用转换器来做到这一点,这涉及以下步骤

1) 创建转换器类,它应该实现IValueConverter

2) 实现Convert 方法,据我了解,您希望根据当前日期执行此操作,因此应该是这样的

//假设您的项目中的日期是可解析的格式

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 代码中声明命名空间

xmlns:src="clr-namespace:PhoneApp1" // src is the name, PhoneApp1 the namespace

然后在 Grid 中将其添加到资源中

<Grid.Resources>
            <src:DateColorConverter x:Key="DateColorConverter" />
</Grid.Resources>

最后在你的 Textblock 中将 ForeGround 设置为

Foreground="{Binding Converter={StaticResource DateColorConverter}}"

这里基本上要做的是,每个对象都将绑定到您的列表中,经过检查并在运行时获取值。

您也可以尝试检查this example,它是希腊语,但通过一些谷歌翻译您就会明白它是如何工作的。

【讨论】:

  • 如何实现转换方法我不知何故迷路了。我是 C# 新手
  • @user3411961只需添加我在转换方法中发布的代码的第一部分
  • 抱歉回复晚了,测试正在进行中。但是如何添加方法的类型,因为它返回了一些东西?我知道 int string void float??
  • 这就是我实现该方法的方式:public object Convert() { 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); }
  • 方法返回对象,在 C# 中一切都继承自 System.Object。你搞定了吗?
猜你喜欢
  • 2018-07-06
  • 1970-01-01
  • 2016-09-30
  • 1970-01-01
  • 1970-01-01
  • 2015-11-06
  • 1970-01-01
  • 1970-01-01
  • 2019-03-01
相关资源
最近更新 更多