Silverlight:与可见性绑定困难

时间:2010-11-30 22:29:01

标签: c# silverlight xaml

我有两个元素:列表框和“此列表为空”消息。我想将它们的可见性绑定到列表框的ItemsSource为空。但是,我不知道该怎么做:

        <TextBlock Text="No favorite searches yet. Add some by searching, then clicking 'Add to Favorites'" 
                   Padding="10,0" 
                   VerticalAlignment="Center"
                   Visibility="{Binding Path=FavoriteFilters.IsEmpty, Converter={StaticResource visibilityConverter}}"
                   />

        <ListBox ItemsSource="FavoriteFilters" 
                 x:Name="favoriteFiltersList" 
                 Visibility="{Binding Path=FavoriteFilters.IsEmpty, Converter={StaticResource visibilityConverter}}">
            <ListBox.ItemTemplate>
                <DataTemplate>
                    <my:FavoriteFilterLink />
                </DataTemplate>
            </ListBox.ItemTemplate>
        </ListBox>

虽然ItemsSource为空,但它们都是可见的。另外,我不知道如何反转ListBox的条件。

可见性转换器:

public class VisibilityConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        if (value is bool?)
        {
            if (string.IsNullOrEmpty((string)parameter))
            {
                return (value as bool?).Value ? Visibility.Visible : Visibility.Collapsed;
            } else
            {
                return (value as bool?).Value ? Visibility.Collapsed : Visibility.Visible;
            }
        }
        throw new ArgumentException();
    }

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

1 个答案:

答案 0 :(得分:1)

你可能最好写两个转换器,一个用于ListBox,另一个用于TextBlock。每个的逻辑都会更简单,您不需要传递参数来获得正确的结果。

虽然它可能不如单个转换器解决方案那么优雅,但它可以更加可维护。

如果您确实要传递参数,则需要使用ConverterParameter

有一个例子here,但我不能100%确定它会满足您的要求。简化的XAML语法是:

<TextBlock Visibility="{Binding FavoriteFilters.IsEmpty,
     Converter={StaticResource visibilityConverter}, ConverterParameter=false}"/>

<ListBox Visibility="{Binding FavoriteFilters.IsEmpty,
     Converter={StaticResource visibilityConverter}, ConverterParameter=true}"/>

然后在您的转换器(简化)中:

bool show = (bool)value;
bool visible = (bool)parameter;
if (visible)
{
    return show ? Visibility.Visible : Visibility.Collapsed;
}
else
{
    return show ? Visibility.Collapsed : Visibility.Visible;
}