【发布时间】:2012-06-13 01:19:53
【问题描述】:
好的,所以我已经研究了好几个小时,但仍然无法弄清楚为什么我的 ViewModel 中的数据没有绑定到我的主页中的 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
现在,当我的程序运行时,我 100% 确定 HomeViewModel 中的数据正在更新,并且每次“设置”新字段时都会调用 NotifyPropertyChanged 方法。
这个类是绑定到 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>
所以这里的 Level、LevelName、PointsNeeded 和 PictureUrl 都是 Profile 中的公共字段(或 CurrentProfile,这是我正在引用的 Profile 的特定实例)。我试过 Profile.[field] 但这也没有用。如果有人能告诉我完成绑定缺少什么,将不胜感激。
顺便说一下,如果这意味着什么,命名空间如下所示
-MainPage 在 MyApp.src.pages
-App 在 MyApp
-HomeViewModel 在 MyApp.src.classes 中
提前感谢您提供有用的解决方案/cmets,如果您需要更多数据/信息,请尽管询问。
【问题讨论】:
-
好吧,我发现一个大问题很有帮助,就是当你声明属性时这样做:"public Profile CurrentProfile {get; set;}" 而不是上面的做法。并对您将在 XAML 中使用 INotifyPropertyChanged 引用的所有其他属性执行相同操作
-
很高兴您解决了您的问题 - 如果您弄清楚问题的真正原因,请发布答案!
-
那里,我在代码部分添加了EDIT,是你的意思吗?
-
我实际上的意思是你应该发布一个答案(下面,在答案部分)但是编辑问题也可以。这样,希望未来的一些用户在遇到同样问题时会发现此信息很有帮助。
标签: c# windows-phone-7 xaml binding mvvm