如何绑定到单例对象实例

How to bind to singleton object instance

所以我有下一个 class,称为 NavigationController,它将控制与导航相关的所有操作 - 菜单、页面、弹出窗口等:

public class NavigationController: INotifyPropertyChanged
{
    #region ~~~ Fields ~~~

    private NavigationController instance;

    private bool isNavigationMenuOpen;

    #endregion
    #region ~~~ Constructors ~~~

    private NavigationController()
    {

    }

    #endregion
    #region ~~~ Events ~~~

    public event PropertyChangedEventHandler PropertyChanged;

    #endregion
    #region ~~~ Properties ~~~

    public NavigationController Instance
    {
        get
        {
            if(instance==null)
            {
                instance = new NavigationController();
            }

            return instance;
        }
    }

    public bool IsNavigationMenuOpen
    {
        get
        {
            return isNavigationMenuOpen;
        }

        set
        {
            if (isNavigationMenuOpen != value)
            {
                isNavigationMenuOpen = value;
                PropertyChanged(this, new PropertyChangedEventArgs("IsNavigationMenuOpen"));
            }
        }
    }

    #endregion
    #region ~~~ Methods ~~~

    public void OpenNavigationMenu()
    {
        this.IsNavigationMenuOpen = true;
    }

    public void CloseNavigationMenu()
    {
        this.IsNavigationMenuOpen = false;
    }

    #endregion
}

在我的 MainPage.xaml 上我有一个菜单,它有一个 属性 IsPaneOpen 并且它是这样绑定的:

IsPaneOpen="{Binding IsNavigationMenuOpen, Source={StaticResource NavigationController}}"

所以我将 NavigationController 添加为资源:

<Page.Resources>
    <controllers:NavigationController x:Key="NavigationController"/>
</Page.Resources>

并得到错误:

XAML NavigationController type cannot be constructed. In order to be constructed in XAML, a type cannot be abstract, interface, nested, generic or a struct, and must have a public default constructor

但是上面的code3没有绑定实例,它会创建新的对象。 如何绑定到实例?

所以按照这里的建议,我改为:

private static NavigationController instance;


public static NavigationController Instance
    {
        get
        {
            if(instance==null)
            {
                instance = new NavigationController();
            }

            return instance;
        }
    }

路径:

<ToggleButton VerticalAlignment="Stretch" HorizontalAlignment="Stretch" IsChecked="{Binding Path=NavigationController.Instance.IsNavigationMenuOpen, Mode=TwoWay, Source={StaticResource NavigationController}}">
        <Image Source="ms-appx:///Assets/Icons/menu-icon.png"></Image>
    </ToggleButton>

并创建构造函数public

当我在一个控件中切换按钮时,另一个控件仍然没有反应。 有什么问题?我认为为每个控件创建了两个实例...

要正确实施单例模式,实例 属性 应该是静态的

您需要在 XAML 中引用该实例 属性。因此,在绑定时,您需要在其中打点(并从实例中删除静态)。

Instance.IsNavigationMenuOpen

但是,如其他答案中所述,请考虑新设计。也许构建一个新类型,公开一个所有其他控制器类型都可以引用的单例实例。这样,至少,它可以理清一些。