【发布时间】:2015-08-03 14:26:45
【问题描述】:
所以我有下一个类,称为 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 类型。为了 在 XAML 中构造的类型不能是抽象的、接口的、嵌套的、 泛型或结构,并且必须具有公共默认构造函数
但是上面的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>
并公开构造函数
当我在一个控件中切换按钮时,另一个控件没有反应。 有什么问题?我认为为每个控件创建了两个实例...
【问题讨论】:
-
"and must have a public default constructor" 似乎错误很明显...要绑定到实例,请将绑定路径设置为该实例,例如@987654326 @.
-
添加了修改请看一下
标签: c# xaml windows-store-apps win-universal-app