2013-10-21 22 views
2

在我App.xaml文件我有:如何從其他窗口使用我的應用程序資源?

<Application.Resources> 
    <LocalViewModels:SharedSettingsViewModel x:Key="SharedSettingsViewModel"/> 
    <LocalViewModels:ApplicationSpecificSettingsViewModel x:Key="ApplicationSpecificSettingsViewModel" /> 
</Application.Resources> 

我怎樣才能在另一個窗口中使用這些資源?

例如,如果我在同一個窗口有這些資源,我會做:

DataContext="{Binding Source={StaticResource ApplicationSpecificSettingsViewModel}}" 
DataContext="{Binding Source={StaticResource ApplicationSpecificSettingsViewModel}}" 
+0

IMO,ViewModels不屬於資源,它們不屬於XAML。 –

+0

@HighCore爲什麼不呢? – FPGA

+0

,因爲它們不是純粹的UI特定的概念。我喜歡VM-First方法,而不是View-First方法。 –

回答

1

雖然我HighCore同意,如果你想這樣做,這是你需要做什麼。以下是一個完整的例子。

第一步 - 創建視圖模型(你已經這樣做看起來是)

namespace resourcesTest 
{ 
    public class SharedViewModel 
    { 
     public string TestMessage 
     { 
      get { return "This is a test"; } 
     } 
    } 
} 

第二步 - 將它添加到App.xaml中的資源

<Application x:Class="resourcesTest.App" 
      xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
      xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
      xmlns:local="clr-namespace:resourcesTest" 
      StartupUri="MainWindow.xaml"> 
    <Application.Resources> 
     <local:SharedViewModel x:Key="SharedViewModel"></local:SharedViewModel> 
    </Application.Resources> 
</Application> 

第三步 - 設置數據上下文在你的窗口 - 無論它是哪一個,然後你可以使用這些數據。

<Window x:Class="resourcesTest.MainWindow" 
     xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
     xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
     Title="MainWindow" Height="350" Width="525"> 
    <Grid DataContext="{Binding Source={StaticResource SharedViewModel}}"> 
     <Label Content="{Binding TestMessage}"></Label> 
    </Grid> 
</Window> 

除非我錯過了你正在嘗試做的事情。再一次,我不會這樣做 - 我只會使用應用程序資源進行樣式和UI特定的事情。希望有幫助。

相關問題