C# WPF用户控件与窗体之间的调用(控件之间相互调用)

要求

有两个用户控件A,B和一个窗体C
A用户控件有一个按钮
在这里插入图片描述

B用户控件是展示的内容
在这里插入图片描述

C窗体有个一个TabControl控件
在这里插入图片描述

A用户控件显示在C窗体上,点击A用户控件的按钮,在C窗体的TabControl中展示用户控件B

代码实现

C窗体代码部分:
前端代码

<Grid>
    <StackPanel>
        <local:UserControl2 x:Name="test111"/>
        <TabControl x:Name="MainTab" Height="340">
            <TabItem Header="TabItem">
                <Grid Background="#FFE5E5E5"/>
            </TabItem>
            <TabItem Header="TabItem">
                <Grid Background="#FFE5E5E5"/>
            </TabItem>
        </TabControl>

    </StackPanel>
</Grid>

后台代码

public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
        test111._mainWindow = this;
    }
}

在这里插入图片描述
用户控件A代码:
前端代码:

<Grid>
    <Button x:Name="ClickBtn" Content="点击" Width="60" Height="40" Click="ClickBtn_Click"/>
</Grid>

后台代码:

public partial class UserControl2 : UserControl
{
    public MainWindow _mainWindow;
    public UserControl2()
    {
        InitializeComponent();
    }
    private void ClickBtn_Click(object sender, RoutedEventArgs e)
    {
        string header = "测试";
        UserControl1 userControl1 = new UserControl1();
        AddOrSelectTabItem(header, userControl1);
    }
    private void AddOrSelectTabItem(string header, object o)
    {

        //MainWindow mainWindow = new MainWindow();
        var tabControl = _mainWindow.MainTab;
        foreach (TabItem item in tabControl.Items)
        {
            if (item.Header.ToString() == header)
            {
                item.IsSelected = true;
                return;
            }
        }
        TabItem temptb = new TabItem();
        temptb.Header = header;
        temptb.Content = o;
        tabControl.Items.Add(temptb);
        tabControl.SelectedIndex = tabControl.Items.Count - 1;
    }
}

实现效果

在这里插入图片描述

  • 2
    点赞
  • 20
    收藏
    觉得还不错? 一键收藏
  • 4
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值