簡體   English   中英

C# (Xamarin) - 如何從“ObservableCollection”訪問對象屬性<T> “?

[英]C# (Xamarin) - How to access an object attribute from an "ObservableCollection<T>"?

我有這個創建ObservableCollection<MenuBody>函數來創建我的 Xamarin.Forms 用戶菜單。

    private ObservableCollection<MenuBody> _userList;
    public ObservableCollection<MenuBody> UserList
    {
        set { SetProperty(ref _userList, value); }
        get { return _userList; }
    }

    private void LoadUserMenu()
    {
        UserList = new ObservableCollection<MenuBody>
        {
            new MenuBody
            {   
                Id = 1,
                Text = "Principal",
                Icon = IconFont.FileSignature,
            },
            new MenuBody
            {
                Id = 2,
                Text = "Configurações",
                Icon = IconFont.Cog,
            },
        };
    }

XAML CollectionView 綁定屬性:

<CollectionView 
    x:Name="MyUserCollectionView"
    BackgroundColor="Transparent" 
    ItemsSource="{Binding UserList}"
    SelectionMode="Single"
    SelectionChangedCommand="{Binding MenuUserTappedCommand}" 
    SelectionChangedCommandParameter="{Binding SelectedItem, 
                                       Source{x:ReferenceMyUserCollectionView}}"
                 

我用來檢測用戶點擊菜單的功能。

     private DelegateCommand<object> _menuUserTappedCommand;

     public DelegateCommand<object> MenuUserTappedCommand =>
    _menuUserTappedCommand ?? (_menuUserTappedCommand = new DelegateCommand<object>(ExecuteMenuUserTappedCommand));

async void ExecuteMenuUserTappedCommand(object parameter)
{
    await App.Current.MainPage.DisplayAlert("Message", "Item " + parameter + " clicked", "Ok");
}

我試圖從這里訪問 MenuBody Id 屬性:

在此處輸入圖片說明

我試圖寫為parameter.Id來引用它,但它沒有按預期顯示。

在此處輸入圖片說明

誰能幫我找出我錯在哪里?

要么投

var item = (MenuBody)parameter;
// then you can use item.Id 

或使用正確的類型而不是對象

public DelegateCommand<MenuBody> MenuUserTappedCommand =>
_menuUserTappedCommand ?? (_menuUserTappedCommand = new DelegateCommand<MenuBody>(ExecuteMenuUserTappedCommand));

async void ExecuteMenuUserTappedCommand(MenuBody parameter)
{
    await App.Current.MainPage.DisplayAlert("Message", "Item " + parameter.Id + " clicked", "Ok");
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM