Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# 'if' Binding value

I've got a list view that is populated by a Binding, on a class named House.

Here's an example of my code:

<DataTemplate DataType="house">
    <TextBlock Text="{Binding sold_status}" />
</DataTemplate>

As you can see, one of my variable names is sold_status. This is a bool.

I want to show either "SOLD" or "NOT SOLD" for 1 and 0 respectively.

Is it possible to fashion an if statement based on the value?

So just so that you can visualise what I want to achieve:

<DataTemplate DataType="house">
    <TextBlock Text="({Binding sold_status} == 1) 'SOLD' else 'NOT SOLD'" />
</DataTemplate>
like image 342
Luke Avatar asked May 25 '26 17:05

Luke


2 Answers

You'll want to create a Style with DataTriggers in to set the properties as needed. You could also use a converter, but changing UI control properties based on underlying data is exactly what triggers/styles are all about.

..In fact, I can see you're basically 'converting' sold_status to a bit of text. For that, use a converter. I'll post a quick example..

See the top answer here: WPF: Display a bool value as "Yes" / "No" - it has an example converter class you could repurpose.

like image 142
Kieren Johnstone Avatar answered May 27 '26 07:05

Kieren Johnstone


Look up the IValueConverter interface for an example. Implement the Convert method to return the text you want to display.

like image 41
Wayne Tanner Avatar answered May 27 '26 05:05

Wayne Tanner



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!