Is the I construct useful in Silverlight / MVVM?

I have inherited a Silverlight project with dubious code quality in general, and there is one design that I'm not sure if I should touch it:

public SomeClass Self { get { return this; } } 

It is used in XAML bindings with parameters that are sometimes complex:

 Visibility="{Binding Self, ConverterParameter=!, Converter={StaticResource SmartAssConverter}}" 

And it is used in the PropertyChanged notification (MVVM Light):

 RaisePropertyChanged("Self"); 

So, is there something stopping me from just doing this:

 Visibility="{Binding ConverterParameter=!, Converter={StaticResource SmartAssConverter}}" 

which, I tested, still looks great?

To paraphrase my question, is the need to “raise the property changed”, making this construct (IMHO ugly)?

Edit: To rephrase again, is there a more elegant solution for notifying related controls that their purpose has changed, or do I need to rework Converters?

+4
source share
3 answers

What if the object (i.e. Self ) changes? When using the Self property, you can use the INotifyPropertyChanged interface to report a binding update. If you delete a property, how would you update?

You can try to do RaisePropertyChanged(string.Empty) , but I don't think it worked.

Typically, converters simply passed the properties they needed, not the whole object. But there is no MultiBinding in Silverlight, so you are limited to one property.

You can either add a new property to your object, which performs the same operation as the converter, or wrap it with another object that adds the property. This is usually the role of the presentation model.

+2
source

I usually implement IChangeTracking and INotifyPropertyChanged , and then follow these steps in the default constructor:

 public SomeClass() { this.PropertyChanged += new PropertyChangedEventHandler(OnNotifiedOfPropertyChanged); } private void OnNotifiedOfPropertyChanged(object sender, PropertyChangedEventArgs e) { if (e != null && !String.Equals(e.PropertyName, "IsChanged", StringComparison.Ordinal)) { this.IsChanged = true; } } 

IsChanged properties change properties of changes, and therefore, you can bind to IsChanged to notify when a class has been changed without having to set the class itself as the "I" property.

+1
source

The code you showed is a little clumsy, but I don’t think it is so bad that I need to redo it. You are correct, you can completely remove the path, and this will work for a one-time binding assessment. However, the troubling part is where the code causes a property change for "I" to overestimate the bindings (big hack ... I will remember this for future use!)

The correct approach is to change the DataContext itself, this is actually a change of self and will re-evaluate the entire binding.

Personally, I would not spend too long on this, I have seen much worse!

+1
source

All Articles