我有一个SettingsFlyout
,其中包含“ShowFormatBar”的切换按钮。当切换时,我希望在我的主窗口上显示或隐藏StackPanel
。
我的切换绑定到我的设置正确,但我无法让主窗口刷新内容。我必须关闭并重新打开应用程序以查看更改。
这是我的设置类:
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实例,但我不知道如何解决这个问题。这是问题吗?如果是这样,我在哪里可以声明主编辑器窗口和MySettings可以访问它的AppSettings?
答案 0 :(得分:1)
找到答案here。在发布这个问题之前我应该再搜索一下了!
需要在App.xaml.cs中实例化Settings类。
public AppSettings Settings = new AppSettings();
然后我可以使用此代码从其他任何地方将DataContext设置为该实例。
this.DataContext = (Application.Current as MyNamespace.App).Settings;