问题
I am trying to create an instance of a C# class from within the XAML markup of my application.
I am trying to use the instance of the C# class inside a <StackPanel></StackPanel> tag, inside a <TabItem></TabItem> tag that I have nested in the <TabControl></TabControl> tag where I have declared the namespace that the C# class belongs to:
<TabControl xmlns:agent="RAgent">
<TabItem Header="R">
<StackPanel>
...
</StackPanel>
</TabItem>
<TabItem Header = "BClass">
<StackPanel>
<agent:BClass />
</StackPanel>
</TabItem>
</TabControl>
The C# class BClass is defined with:
namespace RAgent{
public partial class BClass : UserControl{
public BClass(){
...
}
...
}
}
I know that the C# code compiles and runs correctly, as I have previously run this separate to the rest of the application. However, when I currently try to build my code, I get a compile error in the XAML, on the line:
<agent:BClass />
which says:
The name "BClass" does not exist in the namespace "RAgent"
But BClass clearly does exist in the namespace RAgent, as I have declared the namespace at the top of the BClass.cs file with namespace RAgent{...
What am I doing wrong here? Am I trying to instantiate BClass incorrectly from within the XAML file? How should I do this?
Edit
Ok, so I've edited my .xaml file a bit based on the answer at How to create instance of class in XAML?, and on other bits of information I've picked up from various places.
I've added the line:
xmlns:local="clr-namespace:RAgent">
to the top of the file, and then removing the use of xmlns in the <TabControl> tag, and trying to create an instance of the class through local:
<TabControl>
...
<TabItem Header="BClass">
<StackPanel>
<local:BClass x:Name="BClass" />
</StackPanel>
</TabItem>
</TabControl>
However, I now get a compile error on the line where I'm trying to instantiate the BClass:
<local:BClass x:Name="BClass" />
which says:
A value of type 'BClass' cannot be added to a collection or dictionary of type 'UIElementCollection'.
I tried removing the <StackPanel></StackPanel> tags, and although this removed the above compile error, it left me with one that says:
The name "BClass" does not exist in the namespace "clr-namespace:RAgent"- which it clearly does, as shown by the definition of
BClass...
Anyone know how I can resolve this?
回答1:
I suggest you creating the TabControlin your MainApp and then each TabItemas a UserControl in your project. Then, you can easily instantiate your classes in the corresponding tab by doing
<local:BClass x:Name="BClass"/>
Check Tabs in different XAML views and How to create and use an instance of a class in XAML for a better understanding
来源:https://stackoverflow.com/questions/37047773/xaml-creating-an-instance-of-a-class