我是 windows phone 编程的新手,在创建主菜单时我被卡住了。所以,基本是我想使用列表框显示 5 个类别。类别是静态的。那么我这样做对吗?我可以制作比这更简单的代码吗?这是我现在的代码,使用 VS2012 中的 WP 模板。
如果有人能帮助我理解 MVVM 模式,我真的很感激,
/Views/MainPage.xaml:
<ListBox Grid.Column="1" Margin="-48,0,0,0" ItemsSource="{Binding Categories}">
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Vertical">
<TextBlock Text="{Binding Category}" TextWrapping="Wrap" Style="{StaticResource PhoneTextExtraLargeStyle}" />
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
/ViewModels/MainViewModel.cs
public class MainViewModel : ViewModelBase
{
public MainViewModel()
{
this.Categories = new ObservableCollection<ItemViewModel>();
}
public ObservableCollection<ItemViewModel> Categories { get; private set; }
public bool IsDataLoaded
{
get;
private set;
}
public void LoadData()
{
// Sample data; replace with real data
this.Categories.Add(new ItemViewModel() { Category = "tourist attraction" });
this.Categories.Add(new ItemViewModel() { Category = "hotel" });
this.Categories.Add(new ItemViewModel() { Category = "restaurant" });
this.Categories.Add(new ItemViewModel() { Category = "bars & nightlife" });
this.Categories.Add(new ItemViewModel() { Category = "shopping centre" });
this.IsDataLoaded = true;
}
}
/Views/ItemViewModel.cs
public class ItemViewModel : ViewModelBase
{
private string _category;
public string Category
{
get
{
return _category;
}
set
{
if (value != _category)
{
_category = value;
NotifyPropertyChanged("Category");
}
}
}
}