MAUI中Entry控件Id返回GUID而非设置名称的问题
在Android MAUI中获取Entry控件的x:Name而非GUID值
在MAUI里,VisualElement.Id属性是框架自动生成的唯一GUID,用于内部标识控件,和你在XAML中设置的x:Name没有关联——调试时看到的字段名称是编译器根据x:Name生成的后台代码字段,无法通过Id属性获取。
要获取你需要的标识,有两种可靠的方式:
方式一:使用已设置的StyleId
你已经在XAML中给Entry设置了StyleId="StorageLocation",直接读取这个属性就能得到自定义标识:
public async void Unfocused(object sender, FocusEventArgs e) { var entry = (Entry)sender; var fieldName = entry.StyleId; // 返回"StorageLocation" }
方式二:使用AutomationId获取x:Name的值
如果需要的是x:Name对应的txtStorageLocation,可以给Entry添加AutomationId属性并设置为和x:Name相同的值:
修改后的XAML:
<Entry Text="{Binding StorageLocation}" x:Name="txtStorageLocation" AutomationId="txtStorageLocation" StyleId="StorageLocation" Placeholder="{Binding LocationOrBinPlaceholder}" HorizontalTextAlignment="Center" FontSize="20"/>
然后在事件方法中读取:
public async void Unfocused(object sender, FocusEventArgs e) { var entry = (Entry)sender; var fieldName = entry.AutomationId; // 返回"txtStorageLocation" }
补充说明:x:Name的作用是让编译器在后台生成对应的控件字段,方便你在代码中直接引用(比如txtStorageLocation.Text),但它不会映射到控件的Id属性上,因此无法通过Id获取这个名称。
内容的提问来源于stack exchange,提问作者D. Kermott
相关产品推荐
相关产品推荐

