【发布时间】:2018-02-20 06:39:19
【问题描述】:
我有以下情况。我想显示一个字符串列表。为了实现这一点,我有一个绑定到字符串集合的 ListView。在这个集合中,有一些空字符串。我想要的是在存在空字符串时显示以下文本:“-empty-”。这是我目前得到的(源代码仅用于演示目的):
EmptyStringConverter.cs
public class EmptyStringConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, string language)
{
if (value is string && string.IsNullOrWhiteSpace((string)value))
{
return "-empty-";
}
return value;
}
public object ConvertBack(object value, Type targetType, object parameter, string language)
{
throw new NotImplementedException();
}
}
MainPage.xaml
<Page
x:Class="App1.MainPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:App1"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d">
<Page.Resources>
<local:EmptyStringConverter x:Key="EmptyStringConverter" />
</Page.Resources>
<Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
<ListView x:Name="ListView">
<ListView.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding Converter={StaticResource EmptyStringConverter}}" Margin="0,0,0,5" />
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
</Grid>
</Page>
MainPage.xaml.cs
public sealed partial class MainPage : Page
{
public MainPage()
{
this.InitializeComponent();
var source = new[] { "", "String 1", "String 2" };
ListView.ItemsSource = source;
}
}
当在 EmptyStringConverter 类的 Convert 方法中放置断点时,该方法会在除空字符串之外的每个项目中调用。我怎样才能实现我想要的?
【问题讨论】:
标签: string listview uwp converter