I am writing a class that generates WPF bindings for properties based on their accessibility. Here is the key method:
static Binding getBinding(PropertyInfo prop)
{
var bn = new Binding(prop.Name);
bn.UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged;
if (prop.CanRead && prop.CanWrite)
bn.Mode = BindingMode.TwoWay;
else if (prop.CanRead)
bn.Mode = BindingMode.OneWay;
else if (prop.CanWrite)
bn.Mode = BindingMode.OneWayToSource;
return bn;
}
However, this is not working as expected. CanWrite is true when it should be false. For instance, for this property:
abstract class AbstractViewModel {
public virtual string DisplayName { get; protected set; }
}
class ListViewModel : AbstractViewModel {
//does not override DisplayName
}
I find that the DisplayName property of a ListViewModel is both CanRead and CanWrite. However, if I call prop.GetAccessors(), only the get_DisplayName() accessor is listed.
What is going on here? What do CanRead and CanWrite indicate, if not the protection level of the property? What would be the correct implementation of my method?
If you have a question like that you should first look at the documentation.
CanRead:CanWrite:So, the properties indicate whether there is a
getandsetaccessor, not what their protection level is. One reason for this is that Reflection doesn’t know where are you calling it from, so it doesn’t know whether you can actually access the accessors.What you can do is to find out whether you can access the accessors is to call
GetGetMethod()andGetSetMethod(). If the property doesn’t have publicget/setaccessors, they will returnnull.