2012-09-20 94 views
0

我有一個非MVVM應用程序。在MainWindow中,我有一個帶有多個選項卡的TabControl,每個選項卡都包含一個UserControl。由於這些UserControl具有相似的功能,我從一個從UserControl繼承的基類中派生它們。每個UserControl都有一個名爲EdiContents的文本框。和他們每個人都有一個按鈕:WPF用戶控件繼承3

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

我想在基地用戶控件類來實現Copy_Click:

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

但是基類並不知道EdiContents文本框,這是在宣佈每個UserControl的XAML。你能否建議如何解決這個問題?

謝謝。

回答

1

你可以做這樣的事情。

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

注意您呼叫BaseInitComponentInitializeComponent

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

謝謝您的回答。但我的問題實際上是關於如何從基類中訪問在派生的UserControl的XAML中聲明的TextBox。處理程序本身正常工作,因爲它在我上面發佈的代碼中。 –