[英]Access value from XAML and code behind file
我正在尝试访问一个值,该值应在XAML和文件背后的代码之间共享。 因此,我认为我可以使用x:static
标记扩展 。 这是我的代码:
DetailPage.xaml
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:local="clr-namespace:AppName.Pages.DetailPage;assembly=AppName"
x:Class="AppName.Pages.DetailPage">
<Grid x:Name="masterGrid">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="{x:Static local:DetailPage.Width}" />
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<!-- ... -->
</Grid>
</ContenPage>
DetailPage.xaml.cs
namespace AppName.Pages
{
public partial class DetailPage : ContentPage
{
public static readonly double Width = 40;
// ...
}
}
如果我启动应用程序,我会得到
System.Reflection.TargetInvocationException:调用的目标引发了异常。
如果删除x:static
标记扩展名,则页面工作正常。 我尝试使用不同的名称空间,但没有成功。
解:
在Karel Tamayo的帮助下,我开始工作了:
DetailPage.xaml
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:local="clr-namespace:AppName.Pages;assembly=AppName"
x:Class="AppName.Pages.DetailPage">
<Grid x:Name="masterGrid">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="{x:Static local:DetailPage.Width}" />
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<!-- ... -->
</Grid>
</ContenPage>
DetailPage.xaml.cs
namespace AppName.Pages
{
public partial class DetailPage : ContentPage
{
public static readonly GridLength Width = new GridLength(40, GridUnitType.Absolute);
// ...
}
}
从名称空间可能可以看到, DetailPage
位于文件夹Pages
。
当您分配一个double
GridLength
时,Width属性期望一个GridLength
类型的GridLength
。
在您的DetailPage.xaml.cs中尝试以下操作:
public static readonly GridLength Width = new GridLength(40, GridUnitType.Pixel);
然后再次测试您的应用。 您可以根据需要将单位配置为GridUnitType.Pixel
, GridUnitType.Star
或GridUnitType.Auto
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.