【问题标题】:Property changes in the observable items in my collection is not recognized by XAML binding the entire item绑定整个项目的 XAML 无法识别我的集合中可观察项目的属性更改
【发布时间】:2021-09-02 10:32:45
【问题描述】:

如果我绑定到整个项目,如何让我的可观察项目集合中的项目更新被识别?

我有一个实现INotifyPropertyChanged 的类Codec

public class Codec : INotifyPropertyChanged
{
  private bool _isEnabled;

  public bool IsEnabled
  {
    get => _isEnabled;
    set
    {
      _isEnabled = value;
      OnPropertyChanged();  // Raises PropertyChanged
    }
  }

  ...
}

然后我有一个带有 Codec:s 的可观察集合的视图模型。

public class CodecsViewModel : INotifyPropertyChanged
{
  public ObservableCollection<Codec> Codecs { get; }

  ...
}

还有一个列出编解码器的视图,其中容器的可访问性字符串绑定到每个单独的 Codec 项目:

<CollectionView ItemsSource="{Binding Codecs}">
  <CollectionView.ItemTemplate>
    <DataTemplate>
      <StackLayout
        AutomationProperties.Name="{Binding ., Converter={StaticResource CodecPresenter}}">
        ...
      </StackLayout>
    </DataTemplate>
  </CollectionView.ItemTemplate>
<CollectionView>

当我更改单个Codec 项目的IsEnabled 状态时,我希望更新会触发对我的CodecPresenter 转换器的新调用,以便AutomationProperties.Name 属性得到更新。然而,事实并非如此。

Codecs 集合上手动引发PropertyChanged 没有帮助。有什么方法可以向AutomationProperties.Name 绑定发出信号,尽管项目(参考)保持不变,但项目内容已更改?

【问题讨论】:

    标签: c# xaml xamarin.forms observablecollection inotifypropertychanged


    【解决方案1】:

    为您的模型添加 Self 属性

    public Codec Self {
        get {
            return this;
        }
    }
    
    public bool IsEnabled
      {
        get => _isEnabled;
        set
        {
          _isEnabled = value;
          OnPropertyChanged();  
          OnPropertyChanged(Self);
        }
      }
    

    然后绑定到它

    AutomationProperties.Name="{Binding Self, Converter={StaticResource CodecPresenter}}">
      
    

    这个想法源于 Xamarin 论坛上的 post

    【讨论】:

      猜你喜欢
      • 2010-11-04
      • 2011-09-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多