数据绑定到只能由函数修改的属性

问题描述 投票:0回答:1

我有一个可观察的数据集合,在使用函数之外不得对其进行修改。因此它必须是私有财产。但是我需要将它公开给视图,以便我可以绑定其中的信息。最好的方法是什么?

我的第一个想法是复制内部数据,但随后我需要进行浅复制,如果有更好的方法来做到这一点,那将是大量浪费的工作。

c# data-binding maui
1个回答
0
投票

您可以尝试使用 ReadOnlyObservableCollection Class 来包装您的 ObservableCollection。总而言之,

此类是 ObservableCollection 的只读包装器。如果对底层集合进行更改,ReadOnlyObservableCollection 会反映这些更改。

假设我们要绑定到视图模型中名为 ItemsCollection 的 ObservableCollection。

public class MainPageViewModel 
{

    private readonly ObservableCollection<string> ItemsCollection;
    public ReadOnlyObservableCollection<string> ItemsCollectionReadOnly { get; }

    public MainPageViewModel()
    {

        ItemsCollection = new ObservableCollection<string>();
        ItemsCollectionReadOnly = new ReadOnlyObservableCollection<string>(ItemsCollection);

    }


    //in this class, we could modify the ItemsCollection, and the ReadOnlyObservableCollection also reflect the changes.
    public Command ClickedCommand
    {
        get
        {
            return new Command(() =>
            {

                ItemsCollection.Add("11111");

            });              
        }
    }

}

在 xaml 中,我们只公开 ItemsCollectionReadOnly 属性。在其他类中,我们无法修改 ItemsCollection:

<CollectionView x:Name="mycol" ItemsSource="{Binding ItemsCollectionReadOnly}">

希望有帮助!

© www.soinside.com 2019 - 2024. All rights reserved.