I'm new to WPF. I wish to simply display a <Page>
(Page1.xaml
) within MainWindow.xaml
(a Metro UI MetroWindow component). I am able to display it with a <Frame>
object placed in MainWindow.xaml
. I'd also like to populate DataGrid objects and other components with codebehind, but the second I add a Name=
or x:Name=
to anything within Page1.xaml
, I get this error: "Could not register named object. Cannot register duplicate name 'SuperUniqueName' in this scope."
I have looked at every possible related post and found nothing that fixed the problem. I also tried making the codebehind for the Page1 (Page1.xaml.cs
) use private, which gave a different error I was unable to solve.
I have also successfully added names to elements (without crashing, and able to bind data) within MainWindow.xaml, but not when adding to Page1.xaml.
MainWindow.xaml
<Controls:MetroWindow x:Class="TumorManager2GUI.MainWindow"
xmlns:Controls="clr-namespace:MahApps.Metro.Controls;assembly=MahApps.Metro"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:TumorManager2GUI"
mc:Ignorable="d"
Height="810"
Width="1440">
<Grid>
<Frame
VerticalAlignment="Stretch"
HorizontalAlignment="Stretch"
NavigationUIVisibility="Hidden"
Source="/;component/Page1.xaml"/>
</Grid>
</Controls:MetroWindow>
MainWindow.xaml.cs
/// default "using" hidden
using MahApps.Metro.Controls;
namespace TumorManager2GUI
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : MetroWindow
{
public MainWindow()
{
InitializeComponent();
}
}
}
Page1.xaml
<Page x:Class="TumorManager2GUI.Page1"
xmlns:Controls="clr-namespace:MahApps.Metro.Controls;assembly=MahApps.Metro"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:local="clr-namespace:TumorManager2GUI"
mc:Ignorable="d"
Title="Page1">
<Grid>
<DataGrid x:Name="SuperUniqueName" />
</Grid>
</Page>
Page1.xaml.cs
/// default "using" hidden
using MahApps.Metro.Controls;
namespace TumorManager2GUI
{
/// <summary>
/// Interaction logic for Page1.xaml
/// </summary>
public partial class Page1
{
public Page1()
{
InitializeComponent();
}
}
}
What i expect is there to be no crash when adding Names to elements within , so i can set bindings. Instead, I get the error above.
That's a spurious error created because you used the wrong path in your frame.
Change your Frame source to:
Source="Page1.xaml"/>
I also recommend you use usercontrols rather than pages.
Look into MVVM and viewmodel first navigation.