繁体   English   中英

创建主菜单Windows Phone MVVM模式

[英]Create Main Menu Windows Phone MVVM Pattern

我是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");
            }
        }
    }
}

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

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

就像Daniel所说的那样,您的代码没有任何问题,该解决方案与其他解决方案一样好,MVVM是一种体系结构模式,有时您拥有可以阅读和理解的代码要比不懂的严格MVVM代码更好。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM