ListBox和DataGrid的Silverlight模板为空时?

时间:2010-10-24 13:16:47

标签: c# silverlight silverlight-4.0

那么SL4中有没有?

当ListBox和/或DataGrid中没有数据显示为空时,我需要显示某种信息。

如果有人熟悉其中任何一个并且可以提供示例或链接,我将不胜感激。

谢谢,

巫毒

2 个答案:

答案 0 :(得分:1)

我还没有尝试过这个,但你可能会对下面的博客文章链接感兴趣,它为DataGrid提供了一个解决方案,你也可以适应ListBoxes。

http://subodhnpushpak.wordpress.com/2009/05/18/empty-data-template-in-silverlight-datagrid/

答案 1 :(得分:1)

我为99%的案例提供了一个更简单的列表框解决方案。设置为资源后,您只需更改列表框中的标记属性即可使所有功能正常运行。

首先,我修改列表框的默认模板以包含新网格和文本框,如下所示:

原创XAML

<Border Background="{TemplateBinding Background}" BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="{TemplateBinding BorderThickness}" CornerRadius="3" Margin="0">
    <ScrollViewer x:Name="ScrollViewer" Background="Transparent" BorderBrush="Transparent" BorderThickness="0" Margin="0" Padding="0" TabNavigation="{TemplateBinding TabNavigation}">
        <ItemsPresenter Margin="0,0" />
    </ScrollViewer>
</Border>

新XAML

<Border Background="{TemplateBinding Background}" BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="{TemplateBinding BorderThickness}" CornerRadius="3" Margin="0">
    <Grid >
        <TextBlock Text="{Binding RelativeSource={RelativeSource TemplatedParent}, Path=Tag}" VerticalAlignment="Center" HorizontalAlignment="Center" Visibility="{Binding RelativeSource={RelativeSource TemplatedParent}, Path=ItemsSource.Count, Converter={StaticResource ListCount2Visibility}}" Foreground="{StaticResource NormalFontBrush}" FontSize="{StaticResource DefaultFontSize}" />

        <ScrollViewer x:Name="ScrollViewer" Background="Transparent" BorderBrush="Transparent" BorderThickness="0" Margin="0" Padding="0" TabNavigation="{TemplateBinding TabNavigation}">
            <ItemsPresenter Margin="0,0" />
        </ScrollViewer>
    </Grid>
</Border>

textblock visibility属性绑定到名为ListCount2Visibility的自定义转换器,如下所示:

public sealed class ListCount2Visibility : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        if (value != null && (int)value > 0 )
            return "Collapsed";
        else
            return "Visible";

    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        throw new NotImplementedException();
    }
}

值转换器检查ItemSource.Count == 0 ...如果是,则将可见性设置为可见。否则,它就会崩溃。

然后,新文本块的文本属性将绑定到列表框的标记属性。 (这不是理想的,但这是将文本放入控件的最快方法。显然,如果你将tag属性用于其他事情,这将不起作用。)

基本上,您将标记设置为要显示的消息,并且只要列表中没有项目,就会显示文本框(水平和垂直居中)。在开发过程中,您的消息将显示,因为列表为空(假设现在设计时间为datacontext),这样可以直观地显示文本。

这就是它的全部内容。

如果需要,您甚至可以将列表框的tag属性绑定到viewmodel以更改文本。因此,您可以执行诸如“加载....”之类的操作,同时从数据库返回项目,然后在所有内容加载后将其更改为“空列表”消息。 (当然忙碌的指标可能更好)

相关问题