John L.
John L.

Reputation: 1953

Conditional Logic Inside XAML

I am trying to write a component which will show rating via the number of star images it will hold, for example put 5 stars for a rating of 5. Is there a way I can define creation of these stars as a for loop in the XAML or do have to do it programatically in the code behind? What I am asking basically is that, is there a way to incorporate conditional logic inside the XAML?

Upvotes: 0

Views: 1210

Answers (1)

slugster
slugster

Reputation: 49984

is there a way to incorporate conditional logic inside the XAML?

Yes and no. You can use DataTriggers which will be actioned if a condition is met, but that is unnecessary for what you need to do.

I would use a list control, and in the content template for the items have an Image control that uses a star as its source. Bind this list control to a collection (i.e. List<int>) that has one item per star. If it is possible to have fractions of stars then this approach would be best - use a List<decimal> instead of int, then adjust your item template to show the appropriate image for the fractional number.

Alternatively if you just have an int property that contains the number of stars, then there are two approaches:

  • have an Image control that has max stars + 1 DataTriggers, and you set the source of the image to the appropriate image file. This is a somewhat suboptimal method because all the DataTriggers get evaluated.
  • use an Image control with a Converter that returns the appropriate Source URI based on the number of stars.

Upvotes: 1

Related Questions