Xamarin - 是否可以在OnIdiom中包含的xaml元素上使用x:Name?

时间:2017-04-26 11:27:37

标签: xaml xamarin

我有以下情况,我希望使用2种不同的标签,具体取决于我使用的设备(手机或平板电脑)。

<ContentPage xmlns:local="namespace;assembly">
  <ContentPage.Content>

  <Label x:Name="someLabel" Text="Not important"/>
  <!-- some views here -->

    <OnIdiom x:TypeArguments="View">
     <OnIdiom.Phone>
        <Label x:Name="myLabel" Text="{Binding InvoiceURL}"/>
      </OnIdiom.Phone>
     <OnIdiom.Tablet>
        <Label x:Name="myLabelTablet" Text="{Binding InvoiceURL}" />
      </OnIdiom.Tablet>

    </OnIdiom>

    <!-- some views here -->

  </ContentPage.Content> 
</ContentPage>

以下是我希望执行的代码,但由于错误而无法构建:

public MyPage()
    {
      InitializeComponent();
      someLabel.Text = "Hello World";

      if (Device.Idiom == TargetIdiom.Phone)
        doSomething(myLabel);
      else if (Device.Idiom == TargetIdiom.Tablet)
        doSomething(myLabelTablet);
    }

我得到的错误如下:

The name 'myLabel' does not exist in the current context
The name 'myLabelTablet' does not exist in the current context

解决这个问题的好方法是什么? 我收到这些错误的原因是什么?

1 个答案:

答案 0 :(得分:0)

尝试在OnIdiom元素上设置x:名称并访问其PhoneTablet属性。            

  <Label x:Name="someLabel" Text="Not important"/>
  <!-- some views here -->

    <OnIdiom x:Name="myLabel" x:TypeArguments="Label">
     <OnIdiom.Phone>
        <Label Text="{Binding InvoiceURL}"/>
      </OnIdiom.Phone>
     <OnIdiom.Tablet>
        <Label Text="{Binding InvoiceURL}" />
      </OnIdiom.Tablet>

    </OnIdiom>

    <!-- some views here -->

  </ContentPage.Content> 
    </ContentPage>

并在

背后的代码中
public MyPage()
{
    InitializeComponent();
    someLabel.Text = "Hello World";

    if (Device.Idiom == TargetIdiom.Phone)
      doSomething(myLabel.Phone);
    else if (Device.Idiom == TargetIdiom.Tablet)
      doSomething(myLabel.Tablet);
}
相关问题