【发布时间】:2016-04-14 08:06:44
【问题描述】:
我正在尝试创建一个“桌面”页面,以显示图标(程序)。
现在的基本思想是使用 3x3 网格,每个单元格代表一个图标点。
我过去只是直接从我的 ViewModel 调用 View,但我想忠于 MVVM,并认为我会尝试在自定义 Grid 类中使用 DataBinding 和 ObservableCollection 让它工作。
这是我的代码
ViewModel.cs
/*
ViewModel for the DashboardView
*/
public class DashboardViewModel : ViewModelBase
{
INavigationService navigation;
INetworkService network;
public DashboardViewModel(INavigationService _navigation,
INetworkService _network
)
{
navigation = _navigation;
network = _network;
//modelService = _modelService;
Startup();
}
/*
Called when the application starts
*/
public async void Startup()
{
//Bunch of network mumbojumbo that returns a bunch of services as JSON
IList<JToken> results = result["data"]["services"].Children().ToList();
foreach (JToken r in results)
{
ServiceModel temp = JsonConvert.DeserializeObject<ServiceModel>(r.ToString());
Services.Add(temp);
Debug.WriteLine(r);
}
}
/*
Holds all services displayed on the dashboard
*/
public IList<ServiceModel> Services { get; } = new ObservableCollection<ServiceModel>();
这是View.cs中的相关代码
serviceBoard = new DashboardDesktop()
{
VerticalOptions = LayoutOptions.FillAndExpand,
HorizontalOptions = LayoutOptions.FillAndExpand,
BackgroundColor = Color.FromRgb(0.94, 0.94, 0.94),
RowDefinitions =
{
new RowDefinition() { Height = new GridLength(0.333, GridUnitType.Star) },
new RowDefinition() { Height = new GridLength(0.333, GridUnitType.Star) },
new RowDefinition() { Height = new GridLength(0.333, GridUnitType.Star) }
},
ColumnDefinitions =
{
new ColumnDefinition() { Width = new GridLength(0.333, GridUnitType.Star) },
new ColumnDefinition() { Width = new GridLength(0.333, GridUnitType.Star) },
new ColumnDefinition() { Width = new GridLength(0.333, GridUnitType.Star) }
}
};
serviceBoard.SetBinding(DashboardDesktop.ServiceIconsProperty, "Services");
这是我尝试创建我的 ObservableCollection 应该绑定到的 ServiceIcon 属性的自定义网格类
public class DashboardDesktop : Grid
{
public static readonly BindableProperty ServiceIconsProperty =
BindableProperty.Create
(
"ServiceIconsProperty",
typeof(IList<ServiceModel>),
typeof(DashboardDesktop),
null,
BindingMode.OneWay,
(bindable, value) =>
{
return true;
},
(bindable, oldValue, newValue) =>
{
//do stuffs here
//This is random stuff so I could add a breakpoint here
int x = 10;
var b = (IList<ServiceModel>)newValue;
//Determine if an service have been removed or added
});
private IList<ServiceModel> Services { set; get; }
public DashboardDesktop()
{
}
}
现在我尝试在 ServiceIconProperty 的“OnChanged”lambda 函数中放置一个断点,但即使我在 ViewModel 中的 ObservableCollection 中添加了很多元素,它也从未停止过
我做错了什么?
【问题讨论】:
标签: c# mvvm xamarin xamarin.forms