XAML绑定不更新

时间:2015-09-29 17:01:30

标签: c# xaml uwp

我有一个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"/>

VisibilityConverter是一个类:

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,但绑定似乎没有更新。还有其他事需要做吗?

1 个答案:

答案 0 :(得分:2)

  

如果我手动将IsCurrent设置为true,它可以正常工作

对于要通知此类更改的xaml,持有IsCurrent的类需要遵守INotifyPropertyChange,并且IsCurrent的设置者需要启动属性更改通知。然后它将手动以及以编程方式工作。