1

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

1 に答える 1

1

メニューが静的な場合は、表示されたビューモデルを使用したカスタム ユーザー コントロールをお勧めします。

私は ItemViewModel に同意しません。なぜなら、それはビュー モデルを縫い合わせていないからです。その縫い目はモデルであり、INotifyPropertyChanged の実装 (またはあなたが持っている他の基本モデル クラス) である必要があります。ビュー モデルは、データ自体ではなく、データおよび関連するデータ操作のコンテナーとして機能する必要があることに注意してください。

ダニエルが述べたように、コードに問題はありません。このソリューションは他のソリューションと同じくらい優れています。MVVMはアーキテクチャパターンです。理解できない厳密なMVVMコードよりも、読んで理解できるコードの方が良い場合があります

于 2013-01-22T13:10:33.903 に答える