【发布时间】:2020-02-11 19:37:03
【问题描述】:
嘿,我是 Xamarin Forms 的新手,不知何故我看不透那个绑定的东西。
这是我设置 BindingContext 的代码:
public MainPage()
{
InitializeComponent();
BindingContext = new GameViewModel();
}
这里是 ViewModel:
public class GameViewModel
{
private Team Team1 { get; set; }
public Team Team2 { get; set; }
public string Team1Name { get { return Team1.Name; } }
public string StaticString { get { return "static"; } }
}
StaticString 正在工作,绑定 Team1.Name 不显示任何内容,并且 Team1Name 正在引发异常。
这是视图:
<StackLayout Orientation="Horizontal">
<StackLayout Orientation="Vertical">
<Entry Placeholder="{Binding Team1.Name}" />
<Label Text="Welcome to Xamarin.Forms!" />
</StackLayout>
<StackLayout Orientation="Vertical">
<Entry Placeholder="{Binding Team1Name}" />
<Label Text="Welcome to Xamarin.Forms!" />
</StackLayout>
</StackLayout>
我得到的例外是
System.Reflection.TargetInvocationException: 'Exception has been thrown by the target of an invocation.'
【问题讨论】:
-
Team1为空。您已声明它但尚未实例化它。Team1也是私有的,只能绑定到公共属性 -
@Jason 非常感谢,我忘了初始化 Team....
-
您可以在答案中写下您的解决方案并标记它,这将帮助更多有相同问题的人。
标签: c# xamarin.forms model-binding