Vitalik
Vitalik

Reputation: 2754

Is it better to use DataTrigger instead of a databinding?

If I wanted to hide(or change visibility, color, etc) of an element in WPF is it better to use DataTrigger or a binding with a converter?

Sounds like two ways to achieve the same goal. When is it better to user one over another?

Upvotes: 3

Views: 771

Answers (2)

vortexwolf
vortexwolf

Reputation: 14037

I can tell you about my experience.

I use databinding with converters for the following cases:

  1. For the Visibility property (there is the built-in converter in WPF).
  2. In Silverlight applications (although there are silverlight-compatible data triggers in the Microsoft.Expression.Interactions library, they are not as convenient as WPF triggers).
  3. If the source object contains many possible values. Enum to image converter, for example, it is easier to write 5 if-else clauses than 5 datatriggers.

Datatriggers:

  1. If I want to change several different properties at once (background, visibility, thickness).
  2. For brushes (It isn't easy to create brush in C# code by using the hex-number of the color).
  3. If I want to apply static resources.
  4. They can be used for displaying animation and running storyboards.

Sometimes I prefer the MVVM approach: I create additional properties of the necessary type in the viewmodel so that they can be bound directly without converting.

Upvotes: 8

benPearce
benPearce

Reputation: 38333

The short answer is it depends.

Data Triggers only offer equality operations against a single data source.

If you need to have parameters or multi-value binding you would need to use a converter.

Upvotes: 0

Related Questions