XAML绑定未更新
本文关键字:更新 绑定 XAML | 更新日期: 2023-09-27 18:15:00
我有一个GridView
组件,它持有我的项目。当一个项目被选中时,我希望控件在它上面弹出,允许您编辑或删除项目。以下是我用于项目的DataTemplate
:
<Grid Height="200" Width="200">
<Grid.RowDefinitions>
<RowDefinition Height="*"/>
<RowDefinition Height="Auto"/>
</Grid.RowDefinitions>
<Rectangle Grid.Row="0" Fill="White"/>
<TextBlock Grid.Row="0" VerticalAlignment="Center" HorizontalAlignment="Center" Text="No preview image" FontSize="18" Foreground="{ThemeResource TextBoxDisabledBorderThemeBrush}"/>
<Image Style="{StaticResource ProjectCoverImageStyle}" Grid.Row="0"/>
<TextBlock Style="{StaticResource ProjectTitleStyle}" Text="{Binding Title}" Grid.Row="1"/>
<!--The controls for editing and deleting. Show only when project is selected.-->
<Grid x:Name="ControlsGrid" Visibility="{Binding IsCurrent, Converter={StaticResource VisibilityConverter}}">
<Rectangle Grid.Row="0" Fill="Gray" Opacity="0.5"/>
<StackPanel HorizontalAlignment="Center" VerticalAlignment="Center" Orientation="Horizontal">
<Border Style="{StaticResource RoundButtonStyle}">
<Image Source="/Assets/Icons/Edit.png" Style="{StaticResource RoundButtonIconStyle}"/>
</Border>
<Border Style="{StaticResource RoundButtonStyle}" Tapped="Delete_Project">
<Image Source="/Assets/Icons/Delete.png" Style="{StaticResource RoundButtonIconStyle}"/>
</Border>
</StackPanel>
</Grid>
</Grid>
我像这样定义转换器:
<local:VisibilityConverter x:Key="VisibilityConverter"/>
visible converter是一个类:
public class VisibilityConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, string language)
{
bool visibility = (bool)value;
return visibility ? Visibility.Visible : Visibility.Collapsed;
}
public object ConvertBack(object value, Type targetType, object parameter, string language)
{
Visibility visibility = (Visibility)value;
return (visibility == Visibility.Visible);
}
}
在GridView
中选择一个项目运行如下:
private void Projects_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
if (e.AddedItems.Count < 1)
return;
foreach (Project project in ProjectsGridView.Items)
{
if (ProjectsGridView.SelectedItem != project)
project.IsCurrent = false;
else
{
project.IsCurrent = true;
ViewModel.CurrentProject = ViewModel.Projects[ProjectsGridView.SelectedIndex];
}
}
}
如果我手动设置IsCurrent
为true,它工作得很好。但是,当选择/取消选择项目时,它不会更新。我的代码正确地设置了IsCurrent
,但是绑定似乎没有更新。还有什么需要做的吗?
如果我手动设置IsCurrent为true,它会正常工作
要通知xaml这样的更改,持有IsCurrent
的类需要坚持INotifyPropertyChange
, IsCurrent
的setter需要启动属性更改通知。然后,它将以手动方式和编程方式工作。