【发布时间】:2019-03-18 02:14:22
【问题描述】:
我遇到了 Xamarin 问题。我有一个 XAML ContentPage 文件,它由 StackLayout 中的两个 ContentView (vm:) 组成:
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:local="clr-namespace:Proj1"
xmlns:vm="clr-namespace:Proj1.ViewModels"
x:Class="Proj1.MyMain">
<StackLayout BackgroundColor="{StaticResource MainBG}" Spacing="1">
<vm:DisplayArea />
<vm:ButtonArea />
</StackLayout>
</ContentPage>
两个 vm:为标签和按钮呈现两个 ContentView 区域。为了简单起见,我将它们分开并保持 XAML 文件更小。
所以,一般的,合并 XAML 结构如下所示:
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:local="clr-namespace:Proj1"
xmlns:vm="clr-namespace:Proj1.ViewModels"
x:Class="Proj1.MyMain">
<StackLayout BackgroundColor="{StaticResource MainBG}" Spacing="1">
<ContentView>
...
<Label Grid.Row="0" Grid.Column="1" x:Name="InpRegX" />
...
</ContentView>
<ContentView>
...
<Button ... Clicked="BtnClicked" />
...
</ContentView>
</StackLayout>
</ContentPage>
但我想将两个 ContentView 放在单独的文件中。
DisplayArea 包括一个标签 RegX:
<ContentView xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
x:Class="Proj1.ViewModels.DisplayArea">
...
<Label Grid.Row="0" Grid.Column="1" x:Name="InpRegX" />
...
</ContentView>
namespace Proj1.ViewModels
{
public partial class DisplayArea : ContentView
{
public readonly MyClass RegX; // made public for simplicity
public DisplayArea ()
{
InitializeComponent ();
RegX = new MyClass(InpRegX);
}
}
}
现在我想从按钮时钟执行 DisplayArea.RegX 的 .AddChar() 方法。
namespace Proj1.ViewModels
{
public partial class ButtonArea : ContentView
{
public ButtonArea ()
{
InitializeComponent ();
}
private void BtnClicked(object sender, EventArgs e)
{
var btn = (Button)sender;
DisplayArea.RegX.AddChar(btn.Text); // ERROR!
}
}
}
这会产生编译器错误:
非静态字段、方法或属性“DisplayArea.RegX”需要对象引用
这是因为我通过它的类引用RegX,而不是真正的对象实例。但是如何找到编译器为实例创建的名称?
【问题讨论】:
-
是的,这在某种程度上是同一个问题。谢谢 Stijn。
标签: c# xamarin xamarin.forms