简体   繁体   English

C#'if'绑定值

[英]C# 'if' Binding value

I've got a list view that is populated by a Binding, on a class named House . 我在名为House的类上有一个由Binding填充的列表视图。

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 . 如您所见,我的一个变量名称是sold_status This is a bool . 这是一个bool

I want to show either "SOLD" or "NOT SOLD" for 1 and 0 respectively. 我想分别为10显示“已售出”或“未售出”。

Is it possible to fashion an if statement based on the value? 是否有可能根据价值制定一个if语句?

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>

You'll want to create a Style with DataTriggers in to set the properties as needed. 您需要创建一个带有DataTriggers的样式,以根据需要设置属性。 You could also use a converter, but changing UI control properties based on underlying data is exactly what triggers/styles are all about. 您也可以使用转换器,但基于底层数据更改UI控件属性正是触发器/样式的全部内容。

..In fact, I can see you're basically 'converting' sold_status to a bit of text. ..实际上,我可以看到你基本上'将'sold_status'转换为一些文字。 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. 请参阅此处的最佳答案: WPF:将bool值显示为“是”/“否” - 它有一个示例转换器类,您可以重新调整用途。

Look up the IValueConverter interface for an example. 查找IValueConverter接口以获取示例。 Implement the Convert method to return the text you want to display. 实现Convert方法以返回要显示的文本。

您想使用值转换器

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. 像第一个例子中那样保持绑定,然后让转换器返回一个字符串,如果为true则返回“Sold”等。

I suggest you to use a DataTrigger. 我建议你使用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>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM