简体   繁体   中英

WPF User Control Inheritance 3

I have a non-MVVM application. In the MainWindow, I have a TabControl with several tabs, and each tab contains a UserControl. Because those UserControls have similar features, I derive them from a base class that inherits from UserControl. Each of the UserControls has a TextBox called EdiContents. And each of them has a button:

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

I would like to implement Copy_Click in the base UserControl class:

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

But the base class doesn't know EdiContents TextBox, which is declared in each UserControl's XAML. Could you please suggest how this can be solved?

Thanks.

You can do something like this.

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

Note that you are calling BaseInitComponent after InitializeComponent

XAML behind for derived control

<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>

In your BaseUserControl::BaseInitComponent you simply lookup the button by name and wire up the event.

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
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM