.NET MAUI自定义Handler报CS0131:赋值左侧需为变量、属性或索引器
解决.NET MAUI自定义Handler的CS0131错误
错误根源
MapText方法的第一个参数类型错误:传入了EntryHandler,但实际应该是自定义的CustomEntryHandler,类型不匹配导致编译器无法正确识别handler.PlatformView的赋值操作。- 自定义控件接口
ICustomEntry的属性仅定义了get访问器,不符合MAUI属性映射的双向赋值要求。
修复方案
1. 修正MapText方法的参数类型
将MapText的第一个参数改为CustomEntryHandler,确保类型匹配:
private static void MapText(CustomEntryHandler handler, ICustomEntry entry) { handler.PlatformView?.Text = entry.Text; }
2. 更新接口的属性访问器
给ICustomEntry的属性添加set访问器,支持双向赋值:
public interface ICustomEntry : IView { public string Text { get; set; } public Color TextColor { get; set; } }
3. 完整的修正后代码
CustomEntryHandler
public partial class CustomEntryHandler : ViewHandler<ICustomEntry, EditText> { private static PropertyMapper<ICustomEntry, CustomEntryHandler> CustomEntryMapper = new(ViewMapper) { [nameof(ICustomEntry.Text)] = MapText, }; public CustomEntryHandler(CommandMapper commandMapper = null) : base(CustomEntryMapper, commandMapper) { } protected override EditText CreatePlatformView() { return new EditText(Context); } private static void MapText(CustomEntryHandler handler, ICustomEntry entry) { handler.PlatformView?.Text = entry.Text; } }
接口与自定义控件类
public interface ICustomEntry : IView { public string Text { get; set; } public Color TextColor { get; set; } } public class CustomEntry : View, ICustomEntry { public string Text { get; set; } public Color TextColor { get; set; } }
内容的提问来源于stack exchange,提问作者Marco Antonio Luna Serrano
相关产品推荐
相关产品推荐

