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?
What do CanRead and CanWrite indicate?
If you have a question like that you should first look at the documentation.
CanRead
:
If the property does not have a
get
accessor, it cannot be read.
CanWrite
:
If the property does not have a
set
accessor, it cannot be written to.
So, the properties indicate whether there is a get
and set
accessor, 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()
and GetSetMethod()
. If the property doesn't have public get
/set
accessors, they will return null
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With