我有一个列表视图,其中的数据模板具有文本块,其文本值与数据绑定。
<ListView ItemsSource="{Binding Items}"
Grid.Row="2"
HorizontalAlignment="Left"
Margin="10,70"
Foreground="Red" >
<ListView.ItemTemplate >
<DataTemplate>
<TextBlock x:Name="TextBlock_PlayerOneBid"
TextWrapping="Wrap"
Text="{Binding PlayerOneBid}"
FontSize="20"
FontFamily="ArialBlack"
Height="25"
Width="23"
TextAlignment="Center"
/>
<TextBlock x:Name="TextBlock_PlayerTwoBid"
TextWrapping="Wrap"
Text="{Binding PlayerTwoBid}"
FontSize="20"
FontFamily="ArialBlack"
Height="25"
Width="23"
TextAlignment="Center"
/>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
我在这里遇到的问题是这个数据模板打印了两次。有4个文本块而不是2个。有没有办法从打印中重新定义模板,直到设置了所有值?
设置值的代码。
PlayerOneBid = 1 ;
PlayerTwoBid = 2 ;
答案 0 :(得分:1)
创建一个可见性转换器,当字符串为空或空时返回Collapsed
,否则返回Visible
。
public sealed class EmptyToVisibilityConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, string language)
{
if (value == null) return Visibility.Collapsed;
var str = value.ToString();
return String.IsNullOrEmpty(str) ? Visibility.Collapsed : Visibility.Visible;
}
public object ConvertBack(object value, Type targetType, object parameter, string language)
{
throw new NotImplementedException();
}
}
然后在您的页面上声明资源:
然后在每个TextBlock
添加使用转换器:
<ListView ItemsSource="{Binding Items}"
Grid.Row="2"
HorizontalAlignment="Left"
Margin="10,70"
Foreground="Red" >
<ListView.ItemTemplate >
<DataTemplate>
<TextBlock x:Name="TextBlock_PlayerOneBid"
TextWrapping="Wrap"
Text="{Binding PlayerOneBid}"
Visibility="{Binding PlayerOneBid, Converter={StaticResource EmptyToVisibilityConverter}}"
FontSize="20"
FontFamily="ArialBlack"
Height="25"
Width="23"
TextAlignment="Center"
/>
<TextBlock x:Name="TextBlock_PlayerTwoBid"
TextWrapping="Wrap"
Text="{Binding PlayerTwoBid}"
Visibility="{Binding PlayerTwoBid, Converter={StaticResource EmptyToVisibilityConverter}}"
FontSize="20"
FontFamily="ArialBlack"
Height="25"
Width="23"
TextAlignment="Center"
/>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>