绑定源为空时,控件不被隐藏

时间:2014-03-03 07:04:47

标签: c# wpf xaml

我已将viewmodel设置为page的datacontext,并将pivot数据项与Individual集合属性绑定。但是当有数据时绑定工作正常,但是当数据不可用时,它无法正常工作,我基本上想隐藏ItemsControl下面的文本框,但不知道这段代码有什么问题。

<phone:PivotItem Header="Tweets" Margin="{StaticResource PivotItemMargin}" DataContext="{Binding Tweets}">
                <ScrollViewer>
                    <StackPanel>
                        <ItemsControl ItemsSource="{Binding Result}">
                            <ItemsControl.ItemTemplate>
                                <DataTemplate>
                                    <Grid Margin="0,0,0,30">
                                        <Grid.ColumnDefinitions>
                                            <ColumnDefinition Width="Auto"/>
                                            <ColumnDefinition Width="*"/>
                                        </Grid.ColumnDefinitions>
                                        <Grid.RowDefinitions>
                                            <RowDefinition Height="35" />
                                            <RowDefinition Height="75" />
                                        </Grid.RowDefinitions>

                                        <Image Grid.Column="0" Grid.RowSpan="2" Source="{Binding userImage}" Margin="0,0,10,0" MaxWidth="100" MaxHeight="100" Stretch="UniformToFill" Visibility="{Binding userImage, Converter={StaticResource NullToVisibilityConverter}}" />
                                        <TextBlock Grid.Column="1" Grid.Row="0" Text="{Binding name}" Foreground="{StaticResource AppForegroundHighlightTextBrush}" TextWrapping="NoWrap" TextTrimming="WordEllipsis" FontSize="{StaticResource TitleFontSize}"/>
                                        <TextBlock Grid.Column="1" Grid.Row="1" Text="{Binding ShortTitle}" Foreground="{StaticResource AppForegroundSubtextBrush}" TextWrapping="Wrap" VerticalAlignment="Top" FontSize="{StaticResource SubtextFontSize}"/>
                                    </Grid>
                                </DataTemplate>
                            </ItemsControl.ItemTemplate>
                        </ItemsControl>
                        <TextBlock DataContext="{Binding Tweet}" Grid.Row="2" Text="all Tweets" FontWeight="Bold" Visibility="{Binding hasMore,Converter={StaticResource BooleanToVisibilityConverter}}"/>
                    </StackPanel>
                </ScrollViewer>
            </phone:PivotItem>

1 个答案:

答案 0 :(得分:2)

DataContext为null时,绑定将使用TargetNullValue属性中指定的值。因此,请尝试将TargetNullValue Visibility属性绑定到Collapsedwon't even need converter

.......
<Image 
    .......
    Visibility="{Binding userImage, TargetNullValue=Collapsed}" 
    />
.......