应用程序启动前的WPF绑定集不通知?

应用程序启动前的WPF绑定集不通知?,wpf,data-binding,mvvm,Wpf,Data Binding,Mvvm,理论上,这段代码应该为我提供一个300x300的蓝色背景的窗口,因为窗口的内容绑定到AstRootViewModel类型的对象,但是情况似乎并非如此。我想知道是否会发生这种情况,因为在设置mainWindow.ViewModel属性之前,我不会调用asApplication.Run()。使用snoop检查绑定我有一个空白内容绑定,它被标记为错误,没有错误信息 如果在调用应用程序运行方法之前不会发生属性通知,那么以MVVM友好的方式解决此问题的最佳方法是什么? 我有以下WPF应用程序的入口点:

理论上,这段代码应该为我提供一个300x300的蓝色背景的窗口,因为窗口的内容绑定到AstRootViewModel类型的对象,但是情况似乎并非如此。我想知道是否会发生这种情况,因为在设置mainWindow.ViewModel属性之前,我不会调用asApplication.Run()。使用snoop检查绑定我有一个空白内容绑定,它被标记为错误,没有错误信息

如果在调用应用程序运行方法之前不会发生属性通知,那么以MVVM友好的方式解决此问题的最佳方法是什么?

我有以下WPF应用程序的入口点:

    [STAThread]
    public static void Main()
    {
        settingsSource = LoadSettingsFile(".\\applicationSettings.xml");

        astApplication = new Application();
        mainWindow = new AstWindowView();

        mainWindowModel = new AstRootViewModel();
        dataModel = new AstDataModel(settingsSource);

        mainWindow.ViewModel = mainWindowModel;
        astApplication.MainWindow = mainWindow;
        astApplication.Run();
    }
AstWindowView类实现以下重要代码隐藏:

public partial class AstWindowView : Window
{
    public AstRootViewModel ViewModel
    {
        get { return (AstRootViewModel)GetValue(ViewModelProperty); }
        set { SetValue(ViewModelProperty, value); }
    }

    // Using a DependencyProperty as the backing store for ViewModel.  This enables animation, styling, binding, etc...
    public static readonly DependencyProperty ViewModelProperty =
        DependencyProperty.Register("ViewModel", typeof(AstRootViewModel), typeof(Window), new UIPropertyMetadata(null));

    public AstWindowView()
    {
        InitializeComponent();
    }
}
以及以下重要的XAML

<Window.Resources>
    <ResourceDictionary>
        <ResourceDictionary.MergedDictionaries>
            <ResourceDictionary Source="AstViewResources.xaml"/>
        </ResourceDictionary.MergedDictionaries>
    </ResourceDictionary>
</Window.Resources>
<Window.Content>
    <Binding Path="ViewModel" Mode="Default" UpdateSourceTrigger="PropertyChanged"/>
</Window.Content>

AstViewResources.xaml文件定义以下数据模板

<DataTemplate DataType="{x:Type vm:AstRootViewModel}">
    <vw:AstRootView/>
</DataTemplate>

最后,AstRootView XAML包含以下重要XAML:

<UserControl x:Class="SEL.MfgTestDev.AutomatedSettingsTransfer.View.AstRootView"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
             mc:Ignorable="d" 
             d:DesignHeight="300" d:DesignWidth="300">
    <Grid Background="#FF000CFF"/>
</UserControl>

看起来您没有在任何地方设置AstWindowView的DataContext,并且您的绑定没有明确的源代码集。您是否在调试输出中看到绑定错误,并说明了相关内容?尝试在AstWindowView中的InitializeComponent调用后添加(也可以通过更改XAML中的绑定来实现):


@提交NewbieMissueBetter解决方案:DataContext=“{Binding RelativeSource={RelativeSource Self}”
DataContext = this;