I have an Interface and two classes.
public interface IFieldValue
{
Int64 FieldId { get; set; }
string Value { get; set; }
}
public class CarFieldValue : IFieldValue
{
public Int64 CarId { get; set; }
public Int64 FieldId { get; set; }
public string Value { get; set; }
}
public class HouseFieldValue : IFieldValue
{
public Int64 HouseId { get; set; }
public Int64 FieldId { get; set; }
public string Value { get; set; }
}
Now I have a generic usercontrol for displaying the field values of either Car
or House
. The usercontrol is bound to the according ViewModel.
public class CarViewModel : INotifyPropertyChanged
{
(...)
private ObservableCollection<CarFieldValue> _FieldValues;
public ObservableCollection<CarFieldValue> FieldValues
{
get { return _FieldValues; }
set
{
if (_FieldValues!= value)
{
_FieldValues= value;
SendPropertyChanged("FieldValues");
}
}
}
}
and
public class HouseViewModel : INotifyPropertyChanged
{
(...)
private ObservableCollection<HouseFieldValue> _FieldValues;
public ObservableCollection<HouseFieldValue> FieldValues
{
get { return _FieldValues; }
set
{
if (_FieldValues!= value)
{
_FieldValues= value;
SendPropertyChanged("FieldValues");
}
}
}
}
The usercontrol part looks like this:
public IReadOnlyList<IFieldValues> FieldValues
{
get { return (IReadOnlyList<IFieldValues>)GetValue(FieldValuesProperty); }
set { SetValue(FieldValuesProperty, value); }
}
public static readonly DependencyProperty FieldValuesProperty = DependencyProperty.Register("FieldValues", typeof(IReadOnlyList<IFieldValues>), typeof(FieldValuesControl), new UIPropertyMetadata(null));
The binding takes place in XAML in the Views, e.g. in the CarView:
<myCtrls:FieldValuesControl FieldValues="{Binding MyCarViewModel.FieldValues}" />
I found that solution here]1 and it works so far. But I need to edit (add or remove) items in the usercontrol.
When I use an IList<IFieldValues>
instead of IReadOnlyList<IFieldValues>
the binding doesn't work. There are no binding errors/warnings.
I also tried ICollection<IFieldValues>
without success.
I could use IEnumerable<IFieldValues>
as suggested in the comments but then I can't Add()
items because I can't cast the IEnumerable
.
How can I implement this scenario?
Update
Since I didn't find a better solution I use ObservableCollection<IFieldValues>
on both the ViewModels and the usercontrol. As my ViewModels doesn't do much with the Lists it's not to complicated. Thanks for your help.