How to create and use an instance of a class in XAML (.Net Core 3.0)?

Deadly 提交于 2019-12-11 15:51:45

问题


I am new to WPF and trying to learn by doing.
I created a custom WPF tab called "MyTabClass" defined as a "UserControl" and want to instantiate it two times, each in a new UserControl called "Tab1" and "Tab2", which will both later be referenced into a TabControl of my main WPF app. Unfortunately, I can not get it to work, as I don't know how to instantiate...
I've read and tried several links like How to create instance of class in XAML?, XAML- creating an instance of a class , XAML Namespaces and Namespace Mapping for WPF XAML... but with no luck. Here are the related parts of my code:

In my custom class that I want to instantiate:

<UserControl x:Class="WpfApp1.views.MyTabClass"
             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:WpfApp1.views"
             mc:Ignorable="d" Height="634" Width="899" >
...

In my main App:

<Window x:Class="WpfApp1.MainWindow"
             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:WpfApp1"
             xmlns:views="clr-namespace:WpfApp1.views"
             mc:Ignorable="d"
...

<TabControl Grid.Row="3" Style="{StaticResource tabcontrolStyle}" >
            <TabItem Header="production" Name="Tab1">
                <views:Tab1 />
            </TabItem>
            <TabItem Header="search" Name="Tab2">
                <views:Tab2/>
            </TabItem>
        </TabControl>
...

All my views are under the folder "views" in my main project.
If instead of using "MyTabClass" I copy it twice with the names "Tab1" and "Tab2", everything works fine. The matter is, that I do not want to have two identical wpfs but just only one and instantiate it...
Thanks for any help on this!

来源:https://stackoverflow.com/questions/59070675/how-to-create-and-use-an-instance-of-a-class-in-xaml-net-core-3-0

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!