好的,所以我已经研究了好几个小时,但仍然无法弄清楚为什么我的 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
提前感谢您提供有用的解决方案/评论,如果您需要更多数据/信息,请询问。