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

本文关键字:事件 按钮 添加 WPF 动态 | 更新日期: 2023-09-27 18:33:59

我已经为要继承的所有用户控件做了一个 WPF 基本用户控件。在此基用户控件类中,我希望有一个与单击事件关联的按钮。我把它做成这样:

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 上的按钮时,没有任何触发(鼠标事件或单击事件)。我错过了什么?

提前感谢!

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

您可以尝试模板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;
        }
    }

小缺点是你不能在构造函数中访问 PARTS,所以你必须使用 UserControlLoaded来连接事件(在构造函数中订阅Loaded,在 Loaded 中订阅按钮事件)。

也许在你的代码中添加了新的MouseEventHandler:

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