您可以在这里使用两种方法:一种更简单但更丑陋,一种更复杂但更漂亮。
直接编辑后面的代码
(更简单,但由于高耦合而更丑)
假设我们将有以下 XAML:
<StackLayout Orientation="Vertical">
<Label x:Name="lblOutput" Text="[output]" />
<StackLayout Orientation="Horizontal">
<Button x:Name="btnAdd" Text="+" />
<Button x:Name="btnMinus" Text="-" />
</StackLayout>
</StackLayout>
你可以直接在后面的代码中引用 UI 像这样(简化):
int currentValue = 0;
lblOutput.Text = currentValue.ToString ();
btnAdd.Clicked += delegate {
currentValue++;
lblOutput.Text = currentValue.ToString ();
};
btnMinus.Clicked += delegate {
currentValue--;
lblOutput.Text = currentValue.ToString ();
};
这里的诀窍是使用x:Name,让你可以直接使用后面代码中的元素。
使用 MVVM 方法
(更复杂,但更灵活)
创建一个新类(您的 ViewModel)并实现 INotifyPropertyChanged 接口。将该类绑定到后面的 XAML 代码中的视图,如下所示:
this.BindingContext = new ViewModel ();
现在我们可以有这样的 XAML:
<StackLayout Orientation="Vertical">
<Label Text="{Binding CurrentValue}" />
<StackLayout Orientation="Horizontal">
<Button Text="+" Command="{Binding AddCommand}" />
<Button Text="-" Command="{Binding MinusCommand}" />
</StackLayout>
</StackLayout>
ViewModel 看起来像这样:
public ICommand AddCommand { get; private set; }
public ICommand MinusCommand { get; private set; }
public ViewModel ()
{
AddCommand = new Command (() => {
CurrentValue = CurrentValue+1;
});
MinusCommand = new Command (() => {
CurrentValue = CurrentValue-1;
});
}
public int CurrentValue { get; set; } // You'll need to handle the PropertyChanged events here
您可以在here 和here 阅读更多相关信息。
我希望这会有所帮助!