我有看起来像这样的 XAML 代码;
<?xml version="1.0" encoding="UTF-8"?>
<ContentPage
xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:local="clr-namespace:Japanese;assembly=Japanese"
x:Class="Japanese.GettingStarted"
x:Name="gettingStarted"
Title="Getting Started">
<ContentPage.Content>
我的 C#
using System;
using System.Collections.Generic;
using Xamarin.Forms;
namespace Japanese
{
public partial class GettingStarted : ContentPage
{
public GettingStarted()
{
代码工作正常,但我想知道是否有任何优势,或者在 XAML 中指定 x:Name 是否正常?
是的,是有原因的。但是,如果您还没有找到它们,则可能现在不需要它。
最明显的原因是是否需要从 XAML 引用它。例如,您正在使用数据绑定并使用ListView
.在ListView
上,您可以使用具有上下文操作的简单TextCell
。XAML 可能如下所示(从此处获取并进行了一些调整(:
<ListView ItemsSource="{Binding YourItems}">
<ListView.ItemTemplate>
<DataTemplate>
<ViewCell>
<ViewCell.ContextActions>
<MenuItem Command="{Binding DeleteCommand}" CommandParameter="{Binding .}" Text="Delete" IsDestructive="True" />
</ViewCell.ContextActions>
<StackLayout Padding="15,0">
<Label Text="{Binding title}" />
</StackLayout>
</ViewCell>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
现在,如果您以前使用过数据绑定,您将知道其中MenuItem
的绑定绑定到YourItems
集合中对象的每个实例。
但是,在该集合中的实例上实现删除命令是没有意义的。您可能希望在视图模型上这样做。为此,您必须为页面命名,并引用如下命令:<MenuItem Command="{Binding Source={x:Reference MyPage}, Path=BindingContext.DeleteCommand}" CommandParameter="{Binding .}" Text="Delete" IsDestructive="True" />
其中MyPage
是您在x:Name
属性中输入的值。
其他例子可能在那里,但这是一个突出的例子。如果您不必以任何方式引用该页面,则为其命名不会增加任何实际价值。