2010-02-19 51 views
0

從理論上講,這段代碼應該爲我提供一個帶有藍色背景的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> 

回答

1

它看起來像你不是AstWindowView設置DataContext的任何地方,你的綁定沒有明確的來源組。你看到一個綁定錯誤在調試輸出中說明了這種情況嗎?嘗試在AstWindowView構造函數中InitializeComponent調用後添加(也可以通過更改XAML綁定做到這一點):

DataContext = this; 
+0

@commits newbiemistakesuicide – Firoso 2010-02-20 00:00:44

+0

更好的解決方案: 的DataContext = 「{綁定的RelativeSource = {自我的RelativeSource}}」 – Firoso 2010-02-20 00:20:29

相關問題