私は 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");
}
}
}
}