【问题标题】:C# (Xamarin) - How to access an object attribute from an "ObservableCollection<T>"?C# (Xamarin) - 如何从“ObservableCollection<T>”访问对象属性?
【发布时间】:2020-10-19 14:03:35
【问题描述】:

我有这个函数可以创建一个ObservableCollection&lt;MenuBody&gt; 来创建我的 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 来引用它,但它没有按预期显示。

谁能帮我找出我错在哪里?

【问题讨论】:

  • 您是否尝试过类似使用 DelegateCommand&lt;MenuBody&gt; 而不是 DelegateCommand&lt;object&gt; 的明显方法? (当然ExecuteMenuUserTappedCommand参数有明显变化)
  • 你是完全正确的伙伴。我是编程的初学者。有效!感谢您的时间和回答。

标签: c# xaml xamarin.forms observablecollection


【解决方案1】:

要么施放它

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");
}

【讨论】:

    猜你喜欢
    • 2017-12-01
    • 2012-06-03
    • 2019-09-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多