wwarby
wwarby

Reputation: 2051

Updating binding for ObservableCollection member property without INotifyPropertyChanged

I have a WPF View bound to a ViewModel that implements INotifyPropertyChanged. In that View, I have a DataGrid, the items for which are bound to an ObservableCollection in the ViewModel. The ObservableCollection members themselves do not implement INotifyPropertyChanged. In the DataGrid I have three columns - two editable DatePicker columns and a readonly Checkbox column which should become checked when the user selects a date range that includes the current date.

The bindings work when the view is first loaded, but the binding for the Checkbox is not updated when I change the dates in the other two columns, presumably because the class MyDomainObject is not implementing INotifyPropertyChanged. I really don't want to implement that interface here, because the ObservableCollection is of a type returned from a web service and doing so would force me to create and maintain a copy of that type, and I have a lot of similar scenarios in my application. Is there any way I can force the Checkbox to update? I'd greatly prefer to avoid using code behind if possible - I know how to do it if I have to break that rule.

The following code should approximately illustrate the problem:

XAML:

<DataGrid ItemsSource="{Binding MyDomainObjectCollection}">
    <DataGrid.Columns>

        <DataGridTemplateColumn Header="Start Date">
            <DataGridTemplateColumn.CellTemplate>
                <DataTemplate>
                    <TextBlock Text="{Binding StartDate, StringFormat=d}" />
                </DataTemplate>
            </DataGridTemplateColumn.CellTemplate>
            <DataGridTemplateColumn.CellEditingTemplate>
                <DataTemplate>
                    <DatePicker SelectedDate="{Binding StartDate, UpdateSourceTrigger=PropertyChanged}" />
                </DataTemplate>
            </DataGridTemplateColumn.CellEditingTemplate>
        </DataGridTemplateColumn>

        <DataGridTemplateColumn Header="End Date">
            <DataGridTemplateColumn.CellTemplate>
                <DataTemplate>
                    <TextBlock Text="{Binding EndDate, StringFormat=d}" />
                </DataTemplate>
            </DataGridTemplateColumn.CellTemplate>
            <DataGridTemplateColumn.CellEditingTemplate>
                <DataTemplate>
                    <DatePicker SelectedDate="{Binding EndDate, UpdateSourceTrigger=PropertyChanged}" />
                </DataTemplate>
            </DataGridTemplateColumn.CellEditingTemplate>
        </DataGridTemplateColumn>

        <DataGridTemplateColumn Header="Is Active">
            <DataGridTemplateColumn.CellTemplate>
                <DataTemplate>
                    <CheckBox IsChecked="{Binding IsActive, Mode=OneWay}" IsEnabled="False" />
                </DataTemplate>
            </DataGridTemplateColumn.CellTemplate>
        </DataGridTemplateColumn>

    </DataGrid.Columns>
</DataGrid>

View Model:

public class MyViewModel : INotifyPropertyChanged {

    ObservableCollection<MyDomainObject> _myDomainObjectCollection;

    public ObservableCollection<MyDomainObject> MyDomainObjectCollection {
        get { return this._myDomainObjectCollection; }
        set { this._myDomainObjectCollection = value; this.OnPropertyChanged(); }
    }

    [...]

}

Domain object:

public class MyDomainObject {

    public DateTime StartDate { get; set; }

    public DateTime EndDate { get; set; }

    public bool IsActive {
        get { return StartDate < DateTime.Now && EndDate > DateTime.Now; }
    }

}

Upvotes: 1

Views: 768

Answers (2)

Benedikt Schroeder
Benedikt Schroeder

Reputation: 81

Some years ago I faced the same problem. The solution I found uses dynamic object as a proxy object that implements INotifyPropertyChanged. It hooks to getter and setter by reflection and updates the source object when the proxy changes.

public class DynamicProxy : DynamicObject, INotifyPropertyChanged
{
    private readonly PropertyDescriptorCollection mPropertyDescriptors;


    protected PropertyInfo GetPropertyInfo(string propertyName)
    {
        return
            ProxiedObject.GetType()
                .GetProperties()
                .FirstOrDefault(propertyInfo => propertyInfo.Name == propertyName);
    }

    protected virtual void SetMember(string propertyName, object value)
    {
        var propertyInfo = GetPropertyInfo(propertyName);

        if (propertyInfo.PropertyType == value.GetType())
        {
            propertyInfo.SetValue(ProxiedObject, value, null);
        }
        else
        {
            var underlyingType = Nullable.GetUnderlyingType(propertyInfo.PropertyType);

            if (underlyingType != null)
            {
                var propertyDescriptor = mPropertyDescriptors.Find(propertyName, false);

                var converter = propertyDescriptor.Converter;
                if (converter != null && converter.CanConvertFrom(typeof (string)))
                {
                    var convertedValue = converter.ConvertFrom(value);
                    propertyInfo.SetValue(ProxiedObject, convertedValue, null);
                }
            }
        }
        RaisePropertyChanged(propertyName);
    }

    protected virtual object GetMember(string propertyName)
    {
        return GetPropertyInfo(propertyName).GetValue(ProxiedObject, null);
    }

    protected virtual void OnPropertyChanged(string propertyName)
    {
        if (PropertyChanged != null)
        {
            PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
        }
    }

    protected virtual void RaisePropertyChanged(string propertyName)
    {
        OnPropertyChanged(propertyName);
    }

    #region constructor

    public DynamicProxy()
    {
    }

    public DynamicProxy(object proxiedObject)
    {
        ProxiedObject = proxiedObject;
        mPropertyDescriptors = TypeDescriptor.GetProperties(ProxiedObject.GetType());
    }

    #endregion

    public override bool TryConvert(ConvertBinder binder, out object result)
    {
        if (binder.Type == typeof (INotifyPropertyChanged))
        {
            result = this;
            return true;
        }

        if (ProxiedObject != null && binder.Type.IsInstanceOfType(ProxiedObject))
        {
            result = ProxiedObject;
            return true;
        }
        return base.TryConvert(binder, out result);
    }

    public override bool TryGetMember(GetMemberBinder binder, out object result)
    {
        result = GetMember(binder.Name);
        return true;
    }

    public override bool TrySetMember(SetMemberBinder binder, object value)
    {
        SetMember(binder.Name, value);
        return true;
    }

    #region public properties

    public object ProxiedObject { get; set; }

    #endregion

    #region INotifyPropertyChanged Member

    public event PropertyChangedEventHandler PropertyChanged;

    #endregion
}

Lets say we have a domain object like this:

public class DomainObject
{
    public string Name { get; set; }
}

And this view:

<Window x:Class="WpfApplication1.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="MainWindow" Height="350" Width="525">
<Grid>
    <TextBox 
        VerticalAlignment="Top"
        Text="{Binding Name, UpdateSourceTrigger=PropertyChanged}">            
    </TextBox>
</Grid>
</Window>

And asign a proxy to it like so:

DataContext = new DynamicProxy(new DomainObject());

Upvotes: 1

Jehof
Jehof

Reputation: 35544

If you do not want to implement the INotifyPropertyChanged interface on your domain object you could wrap your DomainObject with a ViewModel that has the same interface as your DomainObject and that implements the INotifyPropertyChanged

public class MyDomainObjectViewModel : INotifyPropertyChanged {

  private MyDomainObject _domainObject;

  public MyDomainObjectViewModel(MyDomainObject domainObject){
    _domainObject = domainObject;
  }

  public DateTime StartDate { 
    get{
      return _domainObject.StartDate;
    }
    set{
      _domainObject.StartDate = value;
      RaisePropertyChanged("StartDate");
      RaisePropertyChanged("IsActive");
    }
  }

  public DateTime EndDate { 
    get{
      return _domainObject.EndDate ;
    }
    set{
      _domainObject.EndDate = value;
      RaisePropertyChanged("EndDate");
      RaisePropertyChanged("IsActive");
    }
  }

  public bool IsActive {
    get { return StartDate < DateTime.Now && EndDate > DateTime.Now; }
  }

}

Your ObservableCollection would be then of type ObservableCollection<MyDomainObjectViewModel>.

Upvotes: 1

Related Questions