您可以使用靜態,您可以讀取和綁定到,使用XAML中的x:Static。我不喜歡做靜態全局設置,因爲它更像是一種反模式。
我認爲你應該考慮控制/依賴注入的反轉。這裏有很多IoC容器,但我通常使用Unity來進行依賴注入。它可在http://prism.codeplex.com
使用IoC,您可以註冊您的設置類,並在您的VM需要的數據,他們可以輕鬆地拉出你想要的設置。你的代碼看起來與此類似(如果使用unity)。
var vm = container.Resolve<SomeViewModel>();
public class SomeViewModel
{
public SomeViewModel(IUnityContainer container)
{
ISomeSettings settings = container.Resolve<ISomeSettings>();
}
}
編輯:或者,這裏是你可能會尋找另一種解決方案:
創建單:
class GlobalSettings : ViewModel
{
private Thickness m_globalGirth;
private static GlobalSettings m_instance = new GlobalSettings();
public GlobalSettings()
{
GlobalGirth = new Thickness(2, 2, 2, 2);
}
public Thickness GlobalGirth
{
get { return m_globalGirth; }
set
{
m_globalGirth = value;
InvokePropertyChanged("GlobalGirth");
}
}
public static GlobalSettings Instance
{
get { return m_instance; }
set { m_instance = value; }
}
}
然後設置您的綁定:
<Window x:Class="WpfApplication3.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:WpfApplication3="clr-namespace:WpfApplication3"
Title="Window1" Height="300" Width="300" MouseDoubleClick="Window_MouseDoubleClick">
<Window.Resources>
<WpfApplication3:GlobalSettings x:Key="settings" />
</Window.Resources>
<Grid>
<Border BorderThickness="{Binding Source={StaticResource settings}, Path=Instance.GlobalGirth}"
BorderBrush="Black"
Width="100"
Height="100" />
</Grid>
</Window>
數據類型是否可以從Settings ViewModel的INotifyPropertyChanged可靠地獲取runtimne上的更改?我一直認爲StaticRessource只會被評估一次? – bitbonk 2009-10-12 07:14:31
是的,絕對。你是對的,StaticResource被評估一次,但這是分配給綁定。然而,從這一點開始,綁定就是「活着的」,所以只要你發射屬性更改通知,任何綁定的綁定都會保持最新狀態。 – 2009-10-12 13:09:24
我如何從其他ViewModel對象訪問此MySettings實例? – bitbonk 2010-03-11 09:26:25