WPF按钮动态添加:事件未触发

时间:2014-12-11 10:19:58

标签: c# wpf dynamic user-controls

我为我继承的所有usercontrol做了一个WPF基本usercontrol。 在这个基本的usercontrol类中,我希望有一个与click事件相关联的按钮。我做到了这样:

public class MBaseUserControl : UserControl
{
  //[...]
    protected override void OnContentChanged(object oldContent, object newContent)
    {
        base.OnContentChanged(oldContent, newContent);

        StackPanel mainPanel = new StackPanel();
        EditButton = new Button();
        EditButton.Height = EditButton.Width = 24;
        EditButton.MouseEnter += EditButton_MouseEnter;
        EditButton.MouseLeave += EditButton_MouseLeave;
        EditButton.Click += new RoutedEventHandler(EditButton_Click);
        EditButton.Background = Brushes.Transparent;
        EditButton.BorderBrush = Brushes.Transparent;
        EditButton.HorizontalAlignment = System.Windows.HorizontalAlignment.Right;
        EditButton.VerticalAlignment = System.Windows.VerticalAlignment.Top;

        StackPanel buttonPanel = new StackPanel();
        Image editButtonImage =     ImageTools.ConvertDrawingImageToWPFImage(Properties.Resources.edit, 24, 24);
        buttonPanel.Children.Add(editButtonImage);

        EditButton.Content = buttonPanel;

        mainPanel.Children.Add(EditButton);
        //Add this to new control
        ((IAddChild)newContent).AddChild(mainPanel);
        SetCMSMode(false);
    }
}

但是当我点击GUI上的按钮时,没有任何东西被触发(鼠标事件或点击事件)。 我错过了什么?

先谢谢!

2 个答案:

答案 0 :(得分:1)

您可以尝试模板UserControl以在其他内容中显示其Content。请注意,它未经测试,但我认为它应该可行。

<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
                    xmlns:l="clr-namespace:DemoUni">
    <ControlTemplate x:Key="SomeKey" TargetType="UserControl">
        <Grid x:Name="PART_Grid">
            <ContentPresenter x:Name="PART_Content" Content="{Binding}"/>
            <!-- ... some other content -->
        </Grid>
    </ControlTemplate>
</ResourceDictionary>

UserControl

的构造函数中
var dictionary = new ResourceDictionary();
// xaml containing control template
dictionary.Source = new Uri("/ProjectName;component/MyUserControlTemplate.xaml", UriKind.Relative);
Template = dictionary["SomeKey"] as ControlTemplate;

访问其他内容Grid为例)

    private Grid _partGrid;
    private Grid PartGrid
    {
        get
        {
            if (_partGrid == null)
                _partGrid = (Grid)Template.FindName("PART_Grid", this);
            return _partGrid;
        }
    }

缺点是您无法在构造函数中访问 PART ,因此您必须使用Loaded UserControl来连接事件(订阅{{ 1}}在构造函数中,订阅Loaded)中的按钮事件。

答案 1 :(得分:0)

可能会在代码中添加新的MouseEventHandler:

EditButton.MouseEnter += new MouseEventHandler(EditButton_MouseEnter);
EditButton.MouseLeave += new MouseEventHandler(EditButton_MouseLeave);