[英]Bind to UIElement in code-behind crashing
在我的代码中,我有一个UIElement变量,可以通过按下某些按钮来设置。 现在,我有了这个变量:
public UIElement currentMenu;
设置为此值:
currentMenu = (UIElement)Resources["Home"];
我是从资源中获取资源的,因此不必在后面的代码中对其进行混乱的管理,一旦解决了此问题,便会将资源导出到单独的ResourceDictionary中。
我的SplitView看起来像这样:
<SplitView x:Name="NavPane" OpenPaneLength="250" CompactPaneLength="50" Content="{x:Bind currentMenu}" DisplayMode="CompactOverlay" IsPaneOpen="False" PaneClosing="NavPane_PaneClosing">
问题就在这时出现,绑定使整个应用程序崩溃,并释放了未捕获的win32异常。 我没有得到任何描述,并且错误代码每次都会更改。 我已经用断点检查了此行为是否实际上是由绑定引起的,确实如此。
如果您对这里可能发生的问题有任何建议,请发布答案。 我将提供所需的任何其他信息(如果合理,我不会将整个项目文件发送给您)
任何帮助表示赞赏!
您正在使用变量而不是属性的问题。
private UIElement currentMenu;
public string CurrentMenu
{
get { return currentMenu; }
set {
currentMenu=value);
OnPropertyChanged("CurrentMenu");
}
}
因此,将Control绑定到“变量”的基本规则:
public
。 要通知UI,您应该实现INotifyPropertyChanged
:
public event PropertyChangedEventHandler PropertyChanged;
public void OnPropertyChanged(string propertyName)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
更新:
您的Bidning
应如下所示:
<SplitView x:Name="NavPane" OpenPaneLength="250" CompactPaneLength="50"
Content="{Binding CurrentMenu}" DisplayMode="CompactOverlay" IsPaneOpen="False"
PaneClosing="NavPane_PaneClosing">
我找到了我问题的答案!
即,这不是做到这一点的方法。 相反,我在SplitView的内容内声明了一个Frame:
<SplitView.Content>
<Frame x:Name="activeMenu"/>
</SplitView.Content>
然后,我使用Frame.Navigate()函数将菜单加载到Frame中:
public MainPage()
{
DataContext = this;
this.InitializeComponent();
SetMenu(0);
}
private void SetMenu(int key)
{
switch (key)
{
case 0:
activeMenu.Navigate(typeof(HomeMenu));
break;
//You can add in as many cases as you need
}
}
然后,您需要将所需的所有菜单设置为项目文件中的单独页面。 在此示例中,HomeMenu.xaml包含人们在启动应用程序时看到的菜单的网格。
这样就解决了问题,但是感谢所有为原始(不幸的是失败的)解决方案做出贡献的人(StepUp)!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.