kovacs lorand
kovacs lorand

Reputation: 906

How to prevent modification of inherited properties?

I added some extra stuff to the standard wpf combobox. In the constructor I set two properties:

public SmartComboBox()
            : base()
        {
            this.IsEditable = true;
            this.IsTextSearchEnabled = false;
            ...
        }

The two properties are inherited from System.Windows.Controls.ComboBox. How do I prevent the modification of these two properties after I set their values in the constructor?

Upvotes: 1

Views: 164

Answers (4)

Dtex
Dtex

Reputation: 2623

What if you override the metadata for the IsEditableProperty and play with PropertyChangedCallBack and CorceValueCallBack? http://msdn.microsoft.com/en-us/library/ms597491.aspx

Upvotes: 1

Trevor Pilley
Trevor Pilley

Reputation: 16423

You can't fully prevent it, the closest you can come is re-declaring the properties as new

public SmartComboBox()
{
    base.IsEditable = true;
    base.IsTextSearchEnabled = false;
    ...
}

public new bool IsEditable { get { return base.IsEditable; } }
public new bool IsTextSearchEnabled { get { return base.IsTextSearchEnabled; } }

The downside to this is that new is not an override, if the object is cast as its parent then the property can be set.

The other option is to wrap the class as Tigran mentioned, however the pita with that is exposing all the other properties you need.

Upvotes: 1

Earlz
Earlz

Reputation: 63935

If IsEditable is marked as virtual, it should be trivial to just do

bool iseditableSet=false;
override bool IsEditable
{
    get;
    set
    {
      if(!iseditableSet){
        iseditableSet=true;
        base.IsEditable=value;
      }else{
        throw Exception...
    }     
}

If it's not marked as virtual, it's harder, but you can use "hiding" to prevent at least your own code from modifying the property without a very explict base. directive.. Of course, this is physically impossible to do though if you are dealing with a function that takes Combobox and it could possibly modify those properties. Just take it as a lesson why properties should almost always be virtual

Upvotes: 0

Tigran
Tigran

Reputation: 62265

Short answer: you can't, as that properties modifiers can not be changed by you. If you want to hide an implementation, just encapsulate ComboBox class inside your class.

public class SmartComboBox {

     private ComboBox _uiCombo = ....
}

And also in addition another thing yet:

In your example, in the code presented, there is no any reason of explicitly calling base() on ctor, as it will be called by CLR

Upvotes: 6

Related Questions