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

.NET MAUI:如何绑定对象中KeyValuePair列表属性

先修正你的app_data类的错误

你的代码里有两处笔误,不先修正的话绑定肯定出问题:

  • 构造函数里m_num_fld = 100后面缺分号
  • kvp_list属性的get/set引用了不存在的m_post_data_kv_list,应该改成m_kvp_list

修正后的app_data类代码:

public class app_data
{
    private Int32 m_num_fld;
    private List<KeyValuePair<String, String>> m_kvp_list;

    public app_data()
    {
        m_num_fld = 100; // 补上缺失的分号
        m_kvp_list = new List<KeyValuePair<String, String>>()
        {
            new KeyValuePair<String, String>( "Key 1", "Value 1" ),
            new KeyValuePair<String, String>( "Key 2", "Value 2" )
        };
    }

    public Int32 num_fld
    {
        get => m_num_fld;
        set => m_num_fld = value;
    }

    public List<KeyValuePair<String, String>> kvp_list
    {
        get => m_kvp_list; // 修正为正确的私有字段
        set => m_kvp_list = value;
    }
}

完成XAML绑定的步骤

  1. 设置页面的BindingContext:在页面后台代码(比如MainPage.xaml.cs)中,将BindingContext指定为app_data的实例:
public MainPage()
{
    InitializeComponent();
    BindingContext = new app_data();
}
  1. 修改CollectionView的绑定逻辑:
    • CollectionView的ItemsSource绑定到kvp_list属性
    • 模板内的Label分别绑定到KeyValuePair自带的Key和Value属性

修改后的XAML代码:

<CollectionView ItemsSource="{Binding kvp_list}">
    <CollectionView.ItemTemplate>
        <DataTemplate>
            <Grid
                RowDefinitions="*,*"
                ColumnDefinitions="3*, *"
                RowSpacing="5">
                <!-- 绑定键值对的Key -->
                <Label 
                    Text="{Binding Key}" 
                    Grid.Row="0"
                    Grid.Column="0"
                    BackgroundColor="White"
                    Padding="0,10,30,10"/>
                <!-- 绑定键值对的Value -->
                <Label
                    Text="{Binding Value}"
                    Grid.Row="1"
                    Grid.Column="0"
                    Grid.ColumnSpan="2"
                    BackgroundColor="LightGrey"
                    Padding="10,10,30,10"
                    Margin="10"/>
            </Grid>
        </DataTemplate>
    </CollectionView.ItemTemplate>
</CollectionView>

额外提示

如果需要数据变化时自动更新UI,建议让app_data类实现INotifyPropertyChanged接口,并在属性赋值时触发PropertyChanged事件。另外,KeyValuePair<TKey,TValue>是值类型,本身不支持属性变更通知,若需修改单个键值对并同步UI,建议自定义一个包含Key和Value属性的类并实现INotifyPropertyChanged。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 21:24:28