2014-01-18 42 views
1

我有一個SettingsFlyout,它包含一個「ShowFormatBar」切換按鈕。切換時,我希望在我的主窗口上顯示或隱藏StackPanel將我的MainWindow中的屬性綁定到SettingsFlyout中的設置

我有切換綁定到我的設置正確,但我不能讓主窗口刷新內容。我必須關閉並重新打開應用才能看到更改。

這裏是我的設置類:

public class AppSettings : INotifyPropertyChanged 
{ 
    Windows.Storage.ApplicationDataContainer localSettings = Windows.Storage.ApplicationData.Current.LocalSettings; 

    private bool _showFormatBar; 
    public bool ShowFormatBar 
    { 
     get 
     { 
      if (localSettings.Values["showFormatBar"] == null) 
       localSettings.Values["showFormatBar"] = true; 

      _showFormatBar = (bool)localSettings.Values["showFormatBar"]; 
      return _showFormatBar; 
     } 
     set 
     { 
      _showFormatBar = value; 
      localSettings.Values["showFormatBar"] = _showFormatBar; 
      NotifyPropertyChanged("ShowFormatBar"); 
      NotifyPropertyChanged("FormatBarVisibility"); 
     } 
    } 

    public event PropertyChangedEventHandler PropertyChanged; 
    protected void NotifyPropertyChanged(string propertyName) 
    { 
     if (PropertyChanged != null) 
     { 
      PropertyChanged(this, new PropertyChangedEventArgs(propertyName)); 
     } 
    } 
} 

MySettingsFlyout.xaml.cs

public sealed partial class MySettingsFlyout: SettingsFlyout 
{ 
    public MySettingsFlyout() 
    { 
     this.InitializeComponent(); 
     AppSettings settings = new AppSettings(); 
     this.DataContext = settings; 
    } 
} 

Editor.xaml.cs

public sealed partial class Editor : Page 
{ 
    public AppSettings settings = new AppSettings(); 

    public Editor() 
    { 
     this.InitializeComponent(); 
     this.DataContext = this; 
    } 

    public Visibility FormatBarVisibility 
    { 
     get { return settings.ShowFormatBar ? Visibility.Visible : Visibility.Collapsed; } 
    } 
} 

Editor.xaml

<StackPanel x:Name="FormatBar" Grid.Column="2" Orientation="Horizontal" HorizontalAlignment="Left" Grid.Row="0" Visibility="{Binding FormatBarVisibility}"> 

當我點擊切換按鈕時,我試過把NotifyPropertyChanged的一個單獨的調用放入MySettings.xaml.cs

我也嘗試將StackPanel的可見性設置爲Visibility="{Binding Source=Settings, Path=FormatBarVisibility}",但這也不起作用。

我有一種感覺,我創建了兩個單獨的,未連接的AppSettings實例,但我不知道如何解決這個問題。這是問題嗎?如果是這樣,我可以在哪裏聲明AppSettings,主編輯器窗口和MySettings都可以訪問它?

回答

1

找到了答案here。在發佈這個問題之前,我應該多搜索一下!

Settings類需要在App.xaml.cs中實例化。

public AppSettings Settings = new AppSettings(); 

然後我就可以從其他地方使用此代碼設置的DataContext到該實例。

this.DataContext = (Application.Current as MyNamespace.App).Settings; 
相關問題