從理論上講,這段代碼應該爲我提供一個帶有藍色背景的300x300窗口,讓窗口的內容綁定到類型爲AstRootViewModel的對象,但是這似乎並不是這樣。我想知道這是發生的,因爲我沒有調用astApplication.Run(),直到我設置了mainWindow.ViewModel屬性。使用snoop檢查綁定我有一個空白的內容綁定,它被標記爲錯誤,沒有錯誤信息。應用程序啓動之前設置的WPF綁定不會通知?
如果在應用程序運行方法被調用之前屬性通知不會發生,那麼以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文件定義S中的以下的DataTemplate
<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>
@commits newbiemistakesuicide – Firoso 2010-02-20 00:00:44
更好的解決方案: 的DataContext = 「{綁定的RelativeSource = {自我的RelativeSource}}」 – Firoso 2010-02-20 00:20:29