3

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>

5 Answers 5

5

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.

Sign up to request clarification or add additional context in comments.

1 Comment

+1 - A converter is definately the way to go. In fact this is such a common problem with bools that I'm surprised there's not a VS code snippet for it.
2

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

Comments

0

You want to use a value converter.

Comments

0

A better approach to this would be to use a converter. Keep the binding as you have done in your first example then have the converter return a string with "Sold" if true etc.

Comments

0

I suggest you to use a DataTrigger. It's quite simple and doesn't require separate converter.

<DataTemplate DataType="house">
    <TextBlock x:Name="Status" Text="SOLD" />
    <DataTemplate.Triggers>
         <DataTrigger Binding="{sold_status}" Value="False">
              <Setter TargetName="Status" Property="Text" Value="NOT SOLD"/>
         </DataTrigger>

    </DataTemplate.Triggers>
</DataTemplate>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.