创建主菜单 Windows Phone MVVM 模式

本文关键字:MVVM 模式 Phone Windows 菜单 创建 | 更新日期: 2023-09-27 17:55:12

我是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;
    }
}
/视图

/项目视图模型.cs

public class ItemViewModel : ViewModelBase
{
    private string _category;
    public string Category
    {
        get
        {
            return _category;
        }
        set
        {
            if (value != _category)
            {
                _category = value;
                NotifyPropertyChanged("Category");
            }
        }
    }
}

创建主菜单 Windows Phone MVVM 模式

如果 Menu 是静态的,我建议使用您显示的视图模型的自定义用户控件。

我不同意 ItemViewModel,因为它没有接缝视图模型,它的接缝是一个模型,它应该只是一个 INotifyPropertyChanged 实现(或您拥有的任何其他基模型类)。请记住,视图模型应作为数据和相关数据操作的容器,而不是数据本身。

就像Daniel所说的那样,你的代码没有任何问题,这个解决方案和其他任何解决方案一样好,MVVM是一种架构模式,有时最好有你可以阅读和理解的代码,而不是你无法理解的严格的MVVM代码。