首页 > 解决方案 > 项目的可观察集合不触发转换器

问题描述

我有一个这样的 xaml(我删除了无用的行)

<Window x:Class="LaRenouvellerieUpdater.MainWindow"
    xmlns:converters="clr-namespace:LaRenouvellerieUpdater.Converters">
<Window.Resources>
    <ResourceDictionary>
        <viewmodel:DataViewModel x:Key="DataViewModel"/>
        <model:PhotosModel x:Key="PhotosModel"/>
        <converters:UriToCachedImageConverter x:Key="UriToCachedImageConverter"/>
    </ResourceDictionary>
</Window.Resources>
<Grid>
    <TabControl>
        <TabItem Header="Posts instagrams">
            <DataGrid ItemsSource="{Binding InstagramsPhotos, Mode=TwoWay}" 
                      DataContext="{Binding Source={StaticResource DataViewModel}}">
                <DataGrid.Columns>
                    <DataGridTemplateColumn Header="Url" Width="*" MaxWidth="150">
                        <DataGridTemplateColumn.CellTemplate>
                            <DataTemplate>
                                <Image>
                                    <Image.Source>
                                        <BitmapImage UriSource="{Binding Path=Url, Converter={StaticResource UriToCachedImageConverter}, Mode=TwoWay}" DecodePixelWidth="150" />
                                    </Image.Source>
                                </Image>
                            </DataTemplate>
                        </DataGridTemplateColumn.CellTemplate>

还有一个像这样的可观察集合:

        private ObservableCollection<PhotosModel> _instagramsPhotos = new ObservableCollection<PhotosModel>();
    public ObservableCollection<PhotosModel> InstagramsPhotos
    {
        get => _instagramsPhotos;
        set
        {
            _instagramsPhotos = value;
            RaisePropertyChanged();
        }
    }

像这样的照片模型:

        public PhotosModel(Action<object, PropertyChangedEventArgs> photosModel_PropertyChanged)
    {
        PropertyChanged = new PropertyChangedEventHandler(photosModel_PropertyChanged);
    }

    private void NotifyPropertyChanged([CallerMemberName] string name = "") => 
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(name));
    private string _url;
    public string Url
    {
        get => _url;
        set
        {
            _url = value;
            NotifyPropertyChanged("Url");
        }
    }

当我在我的 observablecollection 中推送元素时,我的 Converter UriToCachedImage 永远不会触发。我不知道为什么。如果属性被修改但不起作用,我试图将我的可观察集合传递给所有 PhotosModel 以触发它。

谢谢

标签: c#xamlbindingobservablecollectionconverters

解决方案


我通过在我的类中创建一个执行转换器工作的属性来解决这个问题。这不完全是我想要的,但它有效。


推荐阅读