好的,所以我现在一直在研究几个小时,仍然无法弄清楚为什么我的ViewModel中的数据没有绑定到我的主页中的XAML。我甚至开始了一个新项目,并以相同的方式实现它,所以我认为它可能与名称空间或我不太熟悉的东西有关。将C#类绑定到WP7的XAML
当我的应用程序启动时,我创建一个App.cs中的全局ViewModel,我用它将数据绑定到我的XAML视图。
public HomeViewModel ViewModel { get; private set; }
private void Application_Launching(object sender, LaunchingEventArgs e)
{
ViewModel = new HomeViewModel();
(App.Current as App).RootFrame.DataContext = (App.Current as App).ViewModel;
}
然后HomeViewModel看起来是这样的:
public class HomeViewModel : INotifyPropertyChanged
{
/***View Model***/
public event PropertyChangedEventHandler PropertyChanged;
private void NotifyPropertyChanged(String info)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(info));
}
}
public HomeViewModel()
{
PropertyChanged = new PropertyChangedEventHandler(delegate { });
}
public Profile CurrentProfile; /*EDIT: Missing {get;set;} Which is necessary for
*any property, including ones below that I
*referenced in the XAML
*/
public string NotificationImage;
public ButtonPanelPath UniversalButtonPath;
public void setProfile(Profile p)
{
CurrentProfile = p;
NotifyPropertyChanged("CurrentProfile");
}
.
.
....rest of access methods and properties
现在,当我的程序运行,我相信,在HomeViewModel中的数据被更新,NotifyPropertyChanged方法被调用每次100%新的领域是“设置”。
而这个类是绑定到RootFrame的吗?所以我不应该能够在我的主页的xaml中访问这些字段?这是在主电网的堆叠面板的XAML的一部分的例子:
<Border BorderThickness="5" BorderBrush="Aqua" CornerRadius="20">
<StackPanel Name="profileInfo" DataContext="{Binding CurrentProfile}">
<TextBlock Text="{Binding FirstName}" Name="profileName" FontSize="26"
FontWeight="Bold" HorizontalAlignment="Center" />
<StackPanel Orientation="Horizontal">
<StackPanel>
<TextBlock Text="{Binding Level}" Name="userLevel" FontSize="32"
Margin="10,0,0,0"/>
<TextBlock Text="{Binding LevelName}" Name="levelName" FontSize="26"
Margin="10,0,0,0"/>
<TextBlock Text="{Binding PointsNeeded}" Name="pointsBar"
Margin="10,0,0,0"/>
</StackPanel>
<Image x:Name="levelIcon" Source="{Binding PictureUrl}"
Margin="15,0,0,0"/>
</StackPanel>
</StackPanel>
</Border>
所以在这里等级,LevelName,PointsNeeded和PictureUrl在档案(或CurrentProfile所有的公共领域是档案的具体实例我参考了)。我试过配置文件[场],但也没有工作。如果有人能告诉我我错过了什么来完成绑定,那将不胜感激。
顺便说命名空间是如下如果这意味着什么
-MainPage是MyApp.src.pages
-APP是MyApp的
-HomeViewModel是MyApp.src.classes
谢谢提前为您提供有用的解决方案/意见,如果您需要更多的数据/信息,请提问。
好吧,所以我发现有一个很大的问题,就是当你声明属性这样做的时候:“public Profile CurrentProfile {get; set;}”,而不是如上所述。对于您将在XAML中使用INotifyPropertyChanged引用的所有其他属性,请执行相同的操作。 – methodMan
很高兴您解决了您的问题 - 如果您找出实际造成问题的原因,请发表回复! –
在那里,我在代码部分添加了编辑,这是你的意思吗? – methodMan