【问题标题】:WPF User Control Inheritance 3WPF用户控件继承3
【发布时间】:2012-09-20 15:15:58
【问题描述】:

我有一个非 MVVM 应用程序。在 MainWindow 中,我有一个带有多个选项卡的 TabControl,每个选项卡都包含一个 UserControl。因为这些 UserControl 具有相似的功能,所以我从继承自 UserControl 的基类派生它们。每个用户控件都有一个名为 EdiContents 的文本框。而且每个人都有一个按钮:

<Button Name="Copy" Content="Copy to Clipboard" Margin="10" Click="Copy_Click" />

我想在基本的 UserControl 类中实现 Copy_Click:

private void Copy_Click(object sender, RoutedEventArgs e)
{
    System.Windows.Forms.Clipboard.SetText(EdiContents.Text);
}

但基类不知道 EdiContents TextBox,它在每个 UserControl 的 XAML 中声明。您能否建议如何解决这个问题?

谢谢。

【问题讨论】:

    标签: c# wpf inheritance user-controls


    【解决方案1】:

    你可以这样做。

    public partial class DerivedUserControl : BaseUserControl
    {
        public DerivedUserControl()
        {
            InitializeComponent();
            BaseInitComponent();
        }
    }
    

    注意你在InitializeComponent之后调用BaseInitComponent

    XAML 用于派生控件

    <app:BaseUserControl x:Class="WpfApplication5.DerivedUserControl"
                         xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                         xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
                         xmlns:app="clr-namespace:WpfApplication5"
                         xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
                         xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
                         >
        <Grid>
            <Button Name="CopyButton"/>
        </Grid>
    </app:BaseUserControl>
    

    在您的 BaseUserControl::BaseInitComponent 中,您只需按名称查找按钮并连接事件。

    public class BaseUserControl : UserControl
    {
        public void BaseInitComponent()
        {
            var button = this.FindName("CopyButton") as Button;
            button.Click += new System.Windows.RoutedEventHandler(Copy_Click);
        }
    
        void Copy_Click(object sender, System.Windows.RoutedEventArgs e)
        {
            //do stuff here
        }
    }
    

    【讨论】:

    • 感谢您的回答。但我的问题实际上是关于如何从派生的 UserControl 的 XAML 中声明的 TextBox 的基类访问。处理程序本身可以正常工作,就像我在上面发布的代码中一样。
    猜你喜欢
    • 2023-03-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-06-10
    • 1970-01-01
    • 2013-09-03
    • 2017-11-14
    相关资源
    最近更新 更多