【发布时间】:2020-06-18 06:00:44
【问题描述】:
在我的 Xamarin Forms 项目中,我使用以下代码在设计时向 xaml 预览器提供模拟数据:
C#:
namespace MyApp.Data
{
public class StaticData
{
private static AppMockData mockData;
public static AppMockData MockData => mockData ?? (mockData = new MockData());
public class MockData
{
public List<MyObj> LstObj { get; set; }
= new List<MyObj>()
{
new MyObj() { P1 = "V1", P2 = "V2" },
new MyObj() { P1 = "V1", P2 = "V2" },
new MyObj() { P1 = "V1", P2 = "V2" }
};
public MyObj SingleObj { get; set; } = new MyObj() { P1 = "V1", P2 = "V2" };
}
}
}
XAML:
<ContentPage xmlns:data="clr-namespace:MyApp.Data"
BindingContext="{x:Static data:StaticData.MockData}"
... >
<ListView x:Name="MyList" ItemsSource="{Binding LstObj}">
...
<Label Text="{Binding P1}" />
<Label Text="{Binding P2}" />
...
</ListView>
然后,在运行时:
var actualListData = GetDataFromDB(); // obj returned is of type List<MyObj>
MyList.ItemsSource = actualListData;
这工作正常。
我想对 SingleObj 做同样的事情,即单个对象,而不是列表。 我试过类似的东西:
<ContentPage xmlns:data="clr-namespace:MyApp.Data"
BindingContext="{x:Static data:StaticData.MockData.SingleObj}"
... >
<Label Text="{Binding P1}" />
<Label Text="{Binding P2}" />
在后面的代码中:
var actualObj = GetDataFromDB(); // obj returned is of type MyObj
this.BindingSource = actualObj;
这在运行时有效,但在设计时无效:“{x:Static data:StaticData.MockData.SingleObj}”未被识别为有效表达式。
我可以让它在设计时和运行时都工作的唯一方法是:
<ContentPage xmlns:data="clr-namespace:MyApp.Data"
BindingContext="{x:Static data:StaticData.MockData}"
... >
<StackLayout x:Name="MyStackLayout" BindingContext="{Binding SingleObj}">
<Label Text="{Binding P1}" />
<Label Text="{Binding P2}" />
</StackLayout>
和:
var actualObj = GetDataFromDB(); // obj returned is of type MyObj
MyStackLayout.BindingContext = actualObj;
这样我就有了一个 StackLayout(仅用于绑定目的),它的 BindingContext 在设计时是 MockData 的属性,在运行时是实际对象。
不知道有没有语法直接在ContentPage BindingContext中指定SingleObj,从而避免把所有东西都放在一个容器布局中。
【问题讨论】:
-
嗨,你解决了吗? ViewModel 会在设计时和运行时产生不同的效果。通常,运行时性能更好。docs.microsoft.com/en-us/xamarin/xamarin-forms/xaml/xaml-basics/…
标签: c# xaml xamarin.forms data-binding