好吧,我遇到了一个问题,我希望得到TextBlock
有的文字,但它不起作用。我被System.NullReferenceException
我已经建立了一个日历,其中日期放在TextBlock
中,现在我想获取此数据并将其与当前日期进行比较,然后突出显示日期。
以下是我使用的代码:
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)
{
string currentItem = null;
currentItem = (sender as TextBlock).Text;
if (currentItem.Equals(DateTime.Today.Date))
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();
}
}
XAML:
<Grid Margin="10,102,10,298">
<GridView ItemsSource="{Binding Calendar.DateCollection}">
<GridView.ItemTemplate>
<DataTemplate>
<Grid x:Name="dateGrid" Background="Black" Width="50" Height="30">
<Grid.Resources>
<local:DateColorConvertor x:Key="DateColorConvertor"/>
</Grid.Resources>
<TextBlock x:Name="txtDate" Text="{Binding}" Foreground="{Binding Converter={StaticResource DateColorConvertor}}" VerticalAlignment="Center" HorizontalAlignment="Center" IsTapEnabled="True"/>
</Grid>
</DataTemplate>
</GridView.ItemTemplate>
</GridView>
</Grid>
答案 0 :(得分:0)
不要这样做。
IValueConverter
接收绑定的值,没有别的。
特别是,该参数称为value
,而不是sender
(source)。
您应该将该值转换为DateTime
并直接使用它。
此外,您可以返回Brushes.Red
。
答案 1 :(得分:0)
您的转换签名看起来与IValueConverter
接口定义的不同。
// Summary:
// Provides a way to apply custom logic to a binding.
public interface IValueConverter
{
// Summary:
// Converts a value.
//
// Parameters:
// value:
// The value produced by the binding source.
//
// targetType:
// The type of the binding target property.
//
// parameter:
// The converter parameter to use.
//
// culture:
// The culture to use in the converter.
//
// Returns:
// A converted value. If the method returns null, the valid null value is used.
object Convert(object value, Type targetType, object parameter, CultureInfo culture);
//
// Summary:
// Converts a value.
//
// Parameters:
// value:
// The value that is produced by the binding target.
//
// targetType:
// The type to convert to.
//
// parameter:
// The converter parameter to use.
//
// culture:
// The culture to use in the converter.
//
// Returns:
// A converted value. If the method returns null, the valid null value is used.
object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture);
转换方法应如下所示:
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
string currentItem = string.Format("{0}", value);
DateTime currentDate = DateTime.MinValue;
if (DateTime.TryParse(currentItem, out currentDate))
{
if (DateTime.Today.Equals(currentDate))
return new SolidColorBrush(Colors.Green);
}
return new SolidColorBrush(Colors.Red);
}