Databinding to a string derived from the Count of

2019-08-11 09:05发布

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}" />

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.

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?

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?

2条回答
小情绪 Triste *
2楼-- · 2019-08-11 09:14

Besides the Converter solution, you could also do it directly in Xaml by changing the Text property to "No Items" when you have no items in the list

<TextBlock Name="tbAlerts">
    <TextBlock.Style>
        <Style TargetType="TextBlock">
            <Setter Property="Text" Value="{Binding Path=Alerts.Count}"/>
            <Style.Triggers>
                <DataTrigger Binding="{Binding Alerts.Count}" Value="0">
                    <Setter Property="Text" Value="No Items"/>
                </DataTrigger>
            </Style.Triggers>
        </Style>
    </TextBlock.Style>
</TextBlock>
查看更多
神经病院院长
3楼-- · 2019-08-11 09:18

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}}"/>
查看更多
登录 后发表回答