2015-08-18 7 views
0

Ну, я застрял в проблеме, где хочу получить текст, который имеет TextBlock, но он не работает. Я застрял с System.NullReferenceExceptionКак получить ссылку на свойство TextBlock.Text

Я построил календарь, в котором даты размещены в 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> 
+1

Не делай этого. Вместо этого привяжите свойство и преобразуйте значение. – SLaks

+0

может помочь мне больше в первый раз, используя C# – user3411961

ответ

0

Не делай этого.

IValueConverter получает связанное значение и ничего больше.

В частности, этот параметр называется value, а не sender (source).
Вы должны просто передать это значение DateTime и использовать его напрямую.

Также вы можете вернуть Brushes.Red.

+0

Я пробовал это, но у меня есть ошибка 'String не была признана действительной DateTime'. Может быть, я получил это неправильно им все еще новичок в этом, хотя здесь коды: 'публичный объект Convert (значение объекта, тип TargetType, параметр объекта, строка языка) { DateTime дт = DateTime.Parse (value.ToString ()); if (dt.Date == DateTime.Now.Date) вернуть новый SolidColorBrush (Colors.Blue); еще вернуть новый SolidColorBrush (Colors.Red); // выбросить новое NotImplementedException(); } ' – user3411961

+0

@ user3411961: Используйте отладчик, чтобы узнать, что такое' значение'. – SLaks

+0

Поскольку значение, которое хранится в текстовом блоке, не в формате 'DateTime', я изменил коды: ' string dt = value.ToString(); if (dt.Equals (DateTime.Now.Date)) вернуть новый SolidColorBrush (Colors.Blue); еще вернуть новый SolidColorBrush (Colors.Red); ' – user3411961

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

метод Convert должен выглядеть следующим образом:

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