0
votes

I'm trying to share one BaseViewModel over multiple Views. Therefore I want to have the ViewModel implement different Interfaces, one for each View.

public class BaseViewModel : IBaseViewModelTypeI, IBaseViewModelTypeII {
    public PropertyI { get; set; }
    public PropertyII { get; set; }
}

public interface IBaseViewModelTypeI {
    PropertyI { get; set; }
}

public interface IBaseViewModelTypeII {
    PropertyII { get; set; }
} 

In my View, I want to set the ViewModel as DataContext and expose only properties which are implemented in the Interface as bindable properties.

But WPF seems to resolve to the BaseType of my BaseViewModel and because of that exposes access to every Property defined in my BaseViewModel.

Is there any way to solve this or is this a bad pattern at all?

1
Rather than resolving to base type it might be using reflection to work with bindings thus whichever type-based limitation you impose would be useless. - Matías Fidemraizer
So, there is no way to restrict the access and I always have to expose every Property of my base class? - flix

1 Answers

0
votes

Rather than resolving to base type, WPF data-binding uses reflection. Check this quote from MSDN:

The binding references are resolved by using either Microsoft .NET Framework reflection or an ICustomTypeDescriptor. Here are three methods for resolving object references for binding [...].

Maybe an approach would be implementing ICustomTypeDescriptor on derived classes of your BaseViewModel instead of using custom interfaces:

The ICustomTypeDescriptor interface allows an object to provide type information about itself. Typically, this interface is used when an object needs dynamic type information. In contrast, the TypeDescriptor class provides static type information that is obtained from metadata [...]