Why variables are not allowed for binding [duplicate] - c#

This question already has answers here:
Why does WPF support binding to properties of an object, but not fields?
(2 answers)
Closed 5 years ago.
I was googling for this point where why the local or global variables are not allowed as sources for WPF data binding; only the wrapping property can be bound to.
So the question is where properties are the wrapper over the variables then why these properties are allowed and the variables are not allowed.
I need to know under the hood system.

The mechanisms used for binding (PropertyDescriptor, DependencyProperties etc.) only use properties, that's the reason you can't bind to fields. Properties can provide validation, change notification and more, which is another reason to prefer properties. Fields provide none of these.
Also, using public fields is usually bad practice, so why should they bother implementing binding to fields? It would only promote those bad practices.

Well, it's not completely true. You can use a field for a binding, but first you have to declare it like a resource and after access it via resource key in binding declaration.
When you're going to bind to code binding to a property is done for be able to iject also OnPorpertyChanged notification too.

Related

How to raise PropertyChangedEventHandler when a sub property is changed in WPF?

I have a property called PriceChangeInPercentWeekly which has other properties like LastOpenPrice, LastClosePrice, etc.
I am changing these continuously. But how can I raise PropertyChangedEventHandler for PriceChangeInPercentWeekly when a sub-property is changed?
When PriceChangeInPercentWeekly itself is changed, I raised it using my custom SetField function. But how can I do this for sub-properties. Because sub-properties do not know the instanced class, right?
PriceChange priceChangeInPercentWeekly;
public PriceChange PriceChangeInPercentWeekly
{
get => this.priceChangeInPercentWeekly;
set => SetField ( ref this.priceChangeInPercentWeekly, value,
"PriceChangeInPercentWeekly"
);
}
Based on the comments, it sounds like you have a issue with properly binding in a collection case. When dealing with collections in MVVM, there are actually 3 seperate kinds of bindings/Change Notifications you need. If any one is missing, you end up getting issues with non-updates pretty quickly:
Whatever class is holding LastOpenPrice, LastClosePrice, PriceChange and the like - it needs change notificaiton on each and every property. Whatever template you use to display that class, needs to properly bind to each of those properties.
You need change notificaiton if anything is added or removed from the Collection. That is the only change notification ObservableCollection<ClassThatHoldsThosePrices> takes care off.
Whatever property exposes the ObservableList<ClassThatHoldsThosePrices> or its Collection View needs change notificaiton as well. ObservableCollections do not support bulk additions. With a big changes you usually have to build a new list in the background, then replace the whole collection.
At this point it usually becomes a question of properly setting up (or automatically having set up) the 3 kinds of bindings. The proper MVVM pattern is not a easy thing to learn and it can not tell if you did it properly, so it is hard to say where the issues could be. About 8 years ago I wrote a short introducing which I think should still be okay-ish for learning the basics: https://social.msdn.microsoft.com/Forums/vstudio/en-US/b1a8bf14-4acd-4d77-9df8-bdb95b02dbe2/lets-talk-about-mvvm?forum=wpf

Why does the XContainer.Nodes() and XElement.Attributes() are methods (not properties)?

A theoretical question now.
As I understand methods are used to implement some sort of behavior and properties are used to retain some state of the object.
I found that XContainer.Nodes() as well as XElement.Attributes() are implemented as methods, not properties. And, IMHO, other methods that should be implemented as properties: XNode.ElementsAfterSelf(), XNode.ElementsBeforeSelf() XNode.NodesAfterSelf() and so forth.
So, everything that returns IEnumerable of something is implemented as method (not property) in Linq to XML.
What is the reason for that? I mean does it serve some specific case or it's just a mistake like for example String.Split() method, that returns char array instead of more expected IEnumerable<char>?
To quote Microsoft "Choosing Between Properties and Methods":
In general, methods represent actions and properties represent data. Properties are meant to be used like fields, meaning that properties should not be computationally complex or produce side effects. When it does not violate the following guidelines, consider using a property, rather than a method, because less experienced developers find properties easier to use.
Consider using a property if the member represents a logical attribute of the type.
For example, BorderStyle is a property because the style of the border is an attribute of a ListView.
Do use a property, rather than a method, if the value of the property is stored in the process memory and the property would just provide access to the value.
You can also read on "Properties vs Methods" here
I like this explanation from that last link
The operation is expensive enough that you want to communicate to the user that they should consider caching the result.

Design strategies to generalize control

I have a GUI control that I need to generalize so it can be used in different situations and I need suggestions. Let me give you some background first. I have a model that stores all my data for a specific application. I access and set the data points through properties in this model.
Right now I am passing the instance of the model to the GUI control and there the client can set/reset/read in the control two specific pieces of data (in the code I am using the properties). That is all good, but now the model has 3 more sets of these two "columns" (six new fields) that also need to be manipulated by the same control in other 3 new different situations. Obviously I don't want to create 3 more copies of this same control (yes, extensibility was not considered when the control was first designed, I know, I know). So, I tried passing a reference to the properties in the control constructor which of course does not work (compiler error: A property, indexer or dynamic member access may not be passed as an out or ref parameter). So, my question is, what would be a good design strategy in this case? How can I generalize this control so it can be reused and it can set/edit these other properties in the model?
Thanks!

What is a dependency property? What is its use? [duplicate]

This question already has answers here:
Closed 11 years ago.
Possiblity:
What is a dependency property?
What is a dependency property? How does it differ from a normal property? What is the purpose of dependency properties? And why it is used, when it is used?
Dependency property: A property that is backed by a DependencyProperty.
The purpose of dependency properties is to provide a way to compute the value of a property based on the value of other inputs.
These other inputs might include system properties such as themes and user preference, just-in-time property determination mechanisms such as data binding and animations/storyboards, multiple-use templates such as resources and styles, or values known through parent-child relationships with other elements in the element tree.
It has Following capabilities:
The property can be set in a style.
The property can be set through data binding.
The property can be set with a dynamic resource reference.
The property can inherit its value automatically from a parent element in the element tree.
The property can be animated.
The property can report when the previous value of the property has been changed and the property value can be coerced.
The property reports information to WPF, such as whether changing a property value should require the layout system to recompose the visuals for an element.
The property receives support in the WPF Designer for Visual Studio. For example, the property can be edited in the Properties window.
(Content taken from MSDN)
Dependency properties store their values outside the class, so properties can be assigned to an object without having to change the object's class. They also support a situation common in WPF where an object may have very many properties, but only a few have non-default values. Dependency properties can have default values, so this reduces memory usage. There is lots more, read the article: Dependency Properties Overview on MSDN.
I think the MSDN article can give you more information.
From what I read is that a Dependency Property relies on other values.
The purpose of dependency properties
is to provide a way to compute the
value of a property based on the value
of other inputs. These other inputs
might include system properties such
as themes and user preference,
just-in-time property determination
mechanisms such as data binding and
animations/storyboards, multiple-use
templates such as resources and
styles, or values known through
parent-child relationships with other
elements in the element tree. In
addition, a dependency property can be
implemented to provide self-contained
validation, default values, callbacks
that monitor changes to other
properties, and a system that can
coerce property values based on
potentially runtime information.
Derived classes can also change some
specific characteristics of an
existing property by overriding
dependency property metadata, rather
than overriding the actual
implementation of existing properties
or creating new properties.
If you are talking about a property with a Dependency attribute (as defined in Microsoft.Practices.Unity)
[Dependency]
public string MyProperty { get; set; }
Then this is used for dependency injection (DI) by the Unity framework. Basically, the property value is set at runtime by the DI framework, rather than being set directly in your code.
However, there is another Dependency attribute defined in System.Runtime.CompilerServices. Please could you update your question with which one you mean.

What are drawbacks of creating a dependency property?

It is said here:
http://msdn.microsoft.com/en-us/library/ms753358.aspx
Sometimes, the typical technique of backing your property with a private field is adequate.
However, you should implement your property as a dependency property whenever you want your property to support one or more of the following WPF capabilities ...
If I look at all the capabilities they are very obvious needs so I can't really see when I should NOT create dependency property.
So if I systematically create a dependency property instead of just creating a private field what would be the drawbacks?
there are in fact some drawbacks:
Creating a Dependency property is more verbose than a private field backed property.
When you use a Dependency property, your data is stored inside a Dictionary. It has some performance implications: The access lookup is done at runtime, the conversion too, and boxing/unboxing will occu because every dependency property values are stored as objects. Furthermore, all these capabilities come for a price (performance price) which you will pay with each access (read or write). Event will be raised (like PropertyChanged) validation will be performed according to your DP configuration...
Your class must inherit from DependencyObject
This is a price I am willing to pay when a need these capabilities. But they aren't needed in a lot of cases=> Use a DP when appropriate, a classic private field elsewhere.
There are case when you will regret that a property is not bindable: When it happens, replace the field with a DP implementation under the hood.
It depends on what you need.
For example if you need binding you MUST create a DependencyProperty.
If you have to work with data that doesn't "communicate" with the graphical interface using a DependencyProperty is worthless and less performant because you don't need binding, animation, etc.
The purpose of dependency properties is to provide a way to compute the value of a property based on the value of other inputs. These other inputs might include system properties such as themes and user preference, just-in-time property determination mechanisms such as data binding and animations/storyboards, multiple-use templates such as resources and styles, or values known through parent-child relationships with other elements in the element tree. In addition, a dependency property can be implemented to provide self-contained validation, default values, callbacks that monitor changes to other properties, and a system that can coerce property values based on potentially runtime information. Derived classes can also change some specific characteristics of an existing property by overriding dependency property metadata, rather than overriding the actual implementation of existing properties or creating new properties.
DP should be used only when you are making / modifying new WPF control. Overhead is too much to be used as property on VM (and makes VM dependant on WPF). For normal usage you should implement INotifyPropertyChanged

Categories