You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Xamarin Picker中获取选项对应的关联Key值

Xamarin Picker绑定Courses集合后获取对应Key的解决方法

核心问题分析

你当前的问题在于没有正确将Picker的选中项转换为Courses对象,直接访问SelectedItem或Items集合元素时,默认是object类型,无法直接获取Key属性。以下是几种可靠的解决方式:


方法1:按钮点击时直接转换SelectedItem

直接将MainPicker.SelectedItem强制转换为Courses类型,即可获取对应的Key:

private void Button_Clicked(object sender, EventArgs e)
{
    // 安全转换选中项为Courses对象
    if (MainPicker.SelectedItem is Courses selectedCourse)
    {
        string targetKey = selectedCourse.Key;
        string hardwareId = hardwareid.Text;
        
        // 执行AES256加密逻辑
        string encryptedResult = YourAes256EncryptMethod(hardwareId, targetKey);
        // 后续处理加密结果
    }
    else
    {
        // 处理未选中任何课程的场景
        Console.WriteLine("请先选择一门课程");
    }
}

方法2:通过SelectedIndexChanged事件提前获取Key

如果需要在选中课程时就拿到Key,可以在SelectedIndexChanged事件中正确转换集合元素:

private void MainPicker_SelectedIndexChanged(object sender, EventArgs e)
{
    var picker = sender as Picker;
    // 排除未选中状态,确保ItemsSource是Courses集合
    if (picker.SelectedIndex != -1 && picker.ItemsSource is IEnumerable<Courses> courseList)
    {
        var selectedCourse = courseList.ElementAt(picker.SelectedIndex);
        string targetKey = selectedCourse.Key;
        // 可以将Key保存到全局变量,供后续加密使用
    }
}

方法3:MVVM模式下的绑定推荐(更优雅)

如果项目采用MVVM架构,建议绑定SelectedItem到ViewModel的属性,自动同步选中的课程对象:

XAML代码:

<Picker ItemsSource="{Binding CourseCollection}"
        ItemDisplayBinding="{Binding Course}"
        SelectedItem="{Binding SelectedCourse}" />

ViewModel代码:

public class YourViewModel : INotifyPropertyChanged
{
    public ObservableCollection<Courses> CourseCollection { get; set; }

    private Courses _selectedCourse;
    public Courses SelectedCourse
    {
        get => _selectedCourse;
        set
        {
            _selectedCourse = value;
            OnPropertyChanged();
            // 选中课程时自动获取Key
            if (_selectedCourse != null)
            {
                CurrentEncryptionKey = _selectedCourse.Key;
            }
        }
    }

    public string CurrentEncryptionKey { get; set; }

    // 按钮命令(替代点击事件)
    public ICommand EncryptCommand => new Command(() =>
    {
        if (!string.IsNullOrEmpty(CurrentEncryptionKey) && !string.IsNullOrEmpty(HardwareId))
        {
            string encryptedResult = YourAes256EncryptMethod(HardwareId, CurrentEncryptionKey);
            // 后续逻辑
        }
    });

    public string HardwareId { get; set; } // 绑定到hardwareid.Text

    // INotifyPropertyChanged实现代码省略
}

注意事项

  • 确保Courses类的Course和Key属性是公共可访问的(public修饰符),否则绑定和转换都会失败。
  • 若使用代码绑定ItemsSource,确保集合是ObservableCollection<Courses>类型,保证数据更新时Picker能同步刷新。

内容的提问来源于stack exchange,提问作者DedSec

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.17 00:31:39