我对Visual Studio和Windows Phone 8的编程非常陌生。我确实熟悉PHP,所以我理解语法的基础知识,尽管与C#略有区别。但是。
无论如何,我只是想通过绑定在一个可以在\ MainPage.xaml中查看的MainPage.xaml.cs变量中创建一个列表,我想这就是它的完成方式。
我现在正努力使它尽可能基本;这是我在代码中的内容:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Navigation;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using lbpme_viewer.Resources;
namespace lbpme_viewer
{
public partial class MainPage : PhoneApplicationPage
{
List<String> MenuItems = new List<String> { "portal", "news", "myprofile", "settings" };
// Constructor
public MainPage()
{
InitializeComponent();
}
}
}
我只会制作4个纯文本块,但我想根据用户的设置删除“myprofile”,但在此之前,我现在只是在一个字符串列表中声明它们。
我的一部分XAML文件:
<!--Panorama item one-->
<phone:PanoramaItem Header="first item">
<!--Single line list with text wrapping-->
<phone:LongListSelector x:Name="menuList" Margin="0,0,-22,0" ItemsSource="{Binding Path=MenuItems}">
<phone:LongListSelector.ItemTemplate>
<DataTemplate>
<StackPanel Margin="0,-6,0,12">
<TextBlock Text="{Binding}" TextWrapping="Wrap" Style="{StaticResource PhoneTextExtraLargeStyle}" FontSize="{StaticResource PhoneFontSizeExtraLarge}"/>
</StackPanel>
</DataTemplate>
</phone:LongListSelector.ItemTemplate>
</phone:LongListSelector>
</phone:PanoramaItem>
显然,这些项目不会显示在LongListSelector中。我不指望它们,因为我知道我缺少一条或多条代码需要这样做,我的问题是,如何?
同样,我只想让MenuList变量中的短语列表出现在我的LongListSelector中,就像创建时默认的panorama / pivot app中的“design one”“design two”一样。
如果它没有太大的不同,我如何从C#代码中获取任何变量以显示在XAML文件中?
谢谢!
答案 0 :(得分:0)
尝试绑定到像这样实现INotifyPropertyChanged的ObservableCollection<string>
List<String> MenuItemsList = new List<String> { "portal", "news", "myprofile", "settings" };
private ObservableCollection<string> _menuItems;
public ObservableCollection<string> MenuItems
{
get { return _menuItems; }
set
{
if (_menuItems == value) return;
_menuItems = value;
NotifyPropertyChanged(); // or NotifyPropertyChanged("MenuItems");
}
}
然后在你的构造函数中通过传入List
来新建ObservableCollectionMenuItems = new ObservableCollection<string>(MenuItemsList);
您的班级(来自http://msdn.microsoft.com/en-us/library/system.componentmodel.inotifypropertychanged(v=vs.110).aspx)
也需要此功能public event PropertyChangedEventHandler PropertyChanged;
// This method is called by the Set accessor of each property.
// The CallerMemberName attribute that is applied to the optional propertyName
// parameter causes the property name of the caller to be substituted as an argument.
private void NotifyPropertyChanged([CallerMemberName] String propertyName = "")
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
看看MVVM Light,它使很多WPF的东西更容易。使用MVVM Light,您的属性可能看起来像这样(并且您不需要所有NotifyPropertyChanged内容)
private ObservableCollection<string> _menuItems;
public ObservableCollection<string> MenuItems
{
get { return _menuItems; }
set
{
if (_menuItems == value) return;
_menuItems = value;
RaisePropertyChanged(() => MenuItems);
}
}