我想显示/隐藏依赖于ListView项的BindingContext值的按钮,所以我创建了一个ValueConverter来将BindingContext转换为布尔值。由于某种原因,它不起作用,即使值为空,按钮也始终可见。
编辑:初始化转换器时返回正确的值,true / false但似乎没有设置IsVisible。 当更改项目时,绑定被绑定到Convert方法不再被调用,这对我来说也很奇怪,因为我希望它在绑定的对象更改值时更新。
这是转换器:
public class NullToBoolConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
return value != null ? true : false;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
//Not used.
throw new NotImplementedException();
}
}
以下是我在XAML中使用它的方法:
<converters:NullToBoolConverter x:Key="objectToBool" />
<DataTemplate x:Key="MyItemTemplate">
<ViewCell>
<Grid ColumnSpacing="10">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="*" />
<ColumnDefinition Width="Auto" />
</Grid.ColumnDefinitions>
<controls:ImageButton Grid.Column="0"
IsVisible="{Binding Path=., Converter={StaticResource objectToBool}}"
VerticalOptions="Start" HorizontalOptions="Center"
Image="ic_remove_circle_outline_black_24dp"
BackgroundColor="Transparent" />
</Grid>
</ViewCell>
</DataTemplate>
列表视图本身就是它的价值
<ListView ItemsSource="{Binding MyItems}"
ItemTemplate="{StaticResource MyItemTemplate}"
RowHeight="50"
HeightRequest="155"
VerticalOptions="Start"
BackgroundColor="#209FAA9F"/>
答案 0 :(得分:2)
根据您显示的代码,您的值转换器似乎不在ResourceDictionary中。尝试通过将NulltoBoolConverter
放在页面的资源字典中来修改您的XAML:
<ContentPage.Resources>
<ResourceDictionary>
<converters:NullToBoolConverter x:Key="objectToBool" />
</ResourceDictionary>
</ContentPage.Resources>