我在Visual Studio 2017中使用Xamarin.Forms。我有Python经验,但是使用C#和XAML进行应用程序开发对我来说是全新的。任何帮助将不胜感激。
namespace FirstApp
{
public partial class MainPage : ContentPage
{
public MainPage()
{
InitializeComponent();
}
private void Calculate
{
Double Num1;
Double Num2;
Answer = (Num1 + Num2).ToString();
}
}
}
<FlexLayout>
<Entry Text="{Binding Num1}"></Entry>
<Entry Text="{Binding Num2}"></Entry>
<Button Text="Go" Clicked="Calculate"></Button>
<Label Text="{Binding Answer}"></Label>
</FlexLayout>
答案 0 :(得分:0)
您正在混淆,您的XAML是绑定到属性,但是没有实现INotifyPropertyChanged
绑定的ViewModel。另外,用作Calculate
事件处理程序的Clicked
方法不会接收EventHandler的参数。如果您想使用MVVM,还需要放弃Commands或Behaviors的事件处理,但这是另一个主题。
以下是使用实现INotifyPropertyChanged
的ViewModel并将Calculate
方法用作Clicked
事件处理程序的方法。
public partial class MainPage : ContentPage
{
public MainPage()
{
InitializeComponent();
BindingContext = new ViewModel();
}
private void Calculate(object sender, System.EventArgs e)
{
ViewModel viewModel = BindingContext as ViewModel;
viewModel.Answer = viewModel.Num1 + viewModel.Num2;
}
}
public class ViewModel : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
private double _num1;
public double Num1
{
get { return _num1; }
set
{
if (_num1 == value)
return;
_num1 = value;
OnPropertyChanged(nameof(Num1));
}
}
private double _num2;
public double Num2
{
get { return _num2; }
set
{
if (_num2 == value)
return;
_num2 = value;
OnPropertyChanged(nameof(Num2));
}
}
private double _answer;
public double Answer
{
get { return _answer; }
set
{
if (_answer == value)
return;
_answer = value;
OnPropertyChanged(nameof(Answer));
}
}
protected void OnPropertyChanged(string propertyname) =>
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyname));
}