数据绑定到从列表计数派生的字符串 [英] Databinding to a string derived from the Count of a List

查看:42
本文介绍了数据绑定到从列表计数派生的字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 TextBlock ,我想将其数据绑定到 List< T> 的计数.有点.

I have a TextBlock, I'd like to databind it to the count of a List<T>. Sort-of.

我可以像这样对它进行数据绑定:

I can databind it like this:

<TextBlock Name="tbAlerts" Text="{Binding Path=Alerts.Count}" />

其中Alerts是 List< String> ,它显示正确的内容.但是,我想在计数为零时显示无警报".

where Alerts is a List<String>, and it displays the correct thing. But, I'd like to display "No alerts" when the count is zero.

我认为实现此目的的一种方法是扩展List,以显示其他字符串属性(称为 CountText ),该属性会发出所需的字符串.当count为零时,它可能会发出无警报",而当 Count == 1 时,它会发出一个警报".那行得通吗?

I thought a way to do this would be to extend List in order to expose an additional string property – call it CountText – that emits the desired string. It might emit "No Alerts" when count is zero, and "One alert" when Count==1. Will that work?

如果执行此操作,如何获取Count中的更改以导致 CountText PropertyChanged 事件,以便在WPF UI中对其进行更新?

If I do this, how would I get the change in Count to result in a PropertyChanged event for CountText, so that it will get updated in the WPF UI?

那是获得我想要的效果的首选方法吗?

is that the preferred way to get the effect I want?

推荐答案

一种实现方法是创建

One way to accomplish that is to create a IValueConverter that would return a string if the value is zero and/or any other number that you want to add custom text to. As for the updating the UI when the count changes, you will have to call the PropertyChanged handler on the list whenever an item is added/removed from the Alerts list.

public class AlertCountConverter : IValueConverter
{

    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        string result = null;
        if (value != null)
        {
            int count = System.Convert.ToInt32(value);
            if (value == 0)
               result = "No Alerts";
            else
               result = count.ToString();
         }
         return result;

     }

     public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
     {
         return new NotImplementedException();
     }
}

<UserControl.Resources>
   <local:AlertCountConverter x:Key="AlertCountConverter"/>
</UserControl.Resources>
<TextBlock x:Name="tbAlerts" Text="{Binding Alerts.Count, Converter={StaticResource AlertCountConverter}}"/>

这篇关于数据绑定到从列表计数派生的字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆