我有一个TextBlock
,我想把它计算为List<T>
的计数。有点。
我可以像这样对它进行数据处理:
<TextBlock Name="tbAlerts" Text="{Binding Path=Alerts.Count}" />
警报是List<String>
,它显示正确的内容。但是,当计数为零时,我想显示“无警报”。
我认为这样做的一种方法是扩展List以暴露一个额外的字符串属性 - 称之为CountText
- 它会发出所需的字符串。当计数为零时,它可能会发出“No Alerts”,而Count==1
时可能会发出“一次警报”。那会有用吗?
如果我这样做,我如何在Count中获得更改,以便为PropertyChanged
生成CountText
事件,以便在WPF UI中更新?
是获得我想要效果的首选方法吗?
答案 0 :(得分:4)
除了Converter解决方案之外,如果列表中没有项目,您也可以通过将Text
属性更改为“无项目”直接在Xaml中执行此操作
<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>
答案 1 :(得分:2)
实现此目的的一种方法是创建IValueConverter,如果值为零,则返回字符串和/或要添加自定义文本的任何其他数字。至于在计数更改时更新UI,只要在“警报”列表中添加/删除项目,就必须在列表上调用PropertyChanged处理程序。
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}}"/>