【问题标题】:Binding to properties in my MainWindow to settings in a SettingsFlyout将 MainWindow 中的属性绑定到 SettingsFlyout 中的设置
【发布时间】:2014-01-18 12:26:54
【问题描述】:

我有一个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 实例,但我不确定如何解决这个问题。这是问题吗?如果是这样,我在哪里可以声明 AppSettings 主编辑器窗口和 MySettings 都可以访问它?

【问题讨论】:

    标签: c# xaml windows-store-apps inotifypropertychanged


    【解决方案1】:

    找到答案here。在发布这个问题之前,我应该多搜索一下!

    Settings 类需要在 App.xaml.cs 中实例化。

    public AppSettings Settings = new AppSettings();
    

    然后,我可以使用此代码从其他任何地方将 DataContext 设置为该实例。

    this.DataContext = (Application.Current as MyNamespace.App).Settings; 
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-07-25
      • 2015-06-29
      • 2011-08-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多