【问题标题】:Binding entire object with converter to text使用转换器将整个对象绑定到文本
【发布时间】:2012-11-10 05:35:09
【问题描述】:

我有一个 ListBox,其中包含整个绑定对象被传递给转换器(需要),并且该对象似乎没有正确更新。这是相关的 XAML

<TextBlock
          Text="{Binding Converter={StaticResource DueConverter}}" 
          FontSize="{StaticResource PhoneFontSizeNormal}" 
          Foreground="{StaticResource PhoneDisabledBrush}" />

还有转换器

public class DueConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        if (value == null) return null;
        Task task = (Task)value;
        if (task.HasReminders)
        {
            return task.Due.Date.ToShortDateString() + " " + task.Due.ToShortTimeString();
        }
        else
        {
            return task.Due.Date.ToShortDateString();
        }
    }

    //Called with two-way data binding as value is pulled out of control and put back into the property
    public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        throw new NotImplementedException();
    }
}

最后是数据模型中的到期日期时间。

private DateTime _due;

    [Column(CanBeNull=false)]
    public DateTime Due
    {
        get { return _due; }
        set
        {
            if (_due != value)
            {
                NotifyPropertyChanging("Due");
                _due = value;
                NotifyPropertyChanged("Due");
            }
        }
    }

NotifyPropertyChanging/Changed 起作用,因为绑定到不同属性的其他控件正确更新。

我的目标是在到期时更新 TextBlock 的到期日期,但输出的格式取决于 Task 对象的另一个属性。

有什么想法吗?

【问题讨论】:

  • 一般来说,SO协议是不把标签放在问题标题中的。我已经更新了你的标题并重新标记了这个问题。

标签: c# binding converter windows-phone


【解决方案1】:

TextBlock.Text 属性绑定到一个 Task 实例,它不关心“Due”。每当您更改“Due”的值时,您还需要引发“Task”的属性更改事件,以便该绑定自行更新。

【讨论】:

  • 我该怎么做?不应该用datacontext中的private void NotifyPropertyChanged(string propertyName) { if (PropertyChanged != null) { PropertyChanged(this, new PropertyChangedEventArgs(propertyName)); } }函数自动引发吗?
  • 如果您绑定到诸如“Due”之类的属性,它会绑定,因为代码在 setter 中调用 NotifyPropertyChanged。但是在您的代码中,您直接绑定到 Task 的一个实例,而不是它的属性。这取决于您如何绑定 Task 实例,但您必须在代码中引发 NotifyPropertyChanged("name_of_your_task_property"),只要您希望 Text="{Binding Converter={StaticResource DueConverter}}" 自行更新。您如何创建/设置用作 ListBox 的 ItemsSource 的数据?
猜你喜欢
  • 1970-01-01
  • 2018-09-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多