在运行时使用UserControl添加一个控件,如何通过在UserControl内部的按钮来移除它?

3
我看到了一些帖子谈论如何在运行时删除已添加的UserControl,但我的问题有点不同。 我有一个UserControl,它由一个带有小“x”按钮的图像组成,该按钮位于右上角,用于从其父级画布中删除自身(UserControl)。 还要注意的是,当用户双击ListboxItem时,在运行时添加了UserControl。 我为右上角按钮编写了Click事件处理程序,但此代码根本未运行。 我知道这是因为我在这个代码中设置了断点,而当我单击按钮时,断点没有被触发。
所以:
1.为什么移除按钮的单击事件没有被处理?
2.也许有更好的实现方式,请给予建议。
下面是用于添加的代码:
    private void MyListBox_MouseDoubleClick(object sender, System.Windows.Input.MouseButtonEventArgs e)
    {
        if (e.OriginalSource.ToString() == "System.Windows.Controls.Border" || e.OriginalSource.ToString() == "System.Windows.Controls.Image" || e.OriginalSource.ToString() == "System.Windows.Controls.TextBlock")
        {
            Expression.Blend.SampleData.MyCollection.Dataset lbi = ((sender as ListBox).SelectedItem as Expression.Blend.SampleData.MyCollection.Dataset);
            var new_usercontrol = new MyUserControl();
            new_usercontrol.MyImageSourceProperty = lbi.Image;
            MyCanvas.Children.Add(new_usercontrol);
            Canvas.SetLeft(new_usercontrol, 100);
            Canvas.SetTop(new_usercontrol, 100);
            Canvas.SetZIndex(new_usercontrol, 100);
        }
    }

以下是UserControl的cs代码:
    public partial class ModuleElement : UserControl
    {

        public ImageSource MyProperty
        {
            get { return (ImageSource)this.image.Source; }
            set { this.image.Source = value; }
        }

        public ModuleElement()
        {
            this.InitializeComponent();
        }

        private void RemoveButton_Click(object sender, RoutedEventArgs e)
        {
            ((Canvas)this.Parent).Children.Remove(this);
        }
    }

XAML代码如下:
<Grid x:Name="LayoutRoot">
    <Image x:Name="image" />
    <Button x:Name="RemoveButton" Content="X" HorizontalAlignment="Right" Height="17.834" Margin="0" VerticalAlignment="Top" VerticalContentAlignment="Center" HorizontalContentAlignment="Center" Click="RemoveButton_Click">
    </Button>
</Grid>

事先感谢您的帮助,

Bryan


2
天啊,通过比较字符串来检查类型,好像仅仅检查类型还不够糟糕!请将这些检查更改为类似于 e.OriginalSource.GetType() == typeof(Border) 或者 e.OriginalSource is Border 的形式(这应该允许子类)。 - H.B.
1个回答

0

所以我在这里尝试了您的代码,除了一些名称更改外,无法重现您的问题。根据我的个人经验,您在这里遇到的问题必须是由于某种原因,单击事件没有正确订阅。为此,我将进入用户控件的设计器中,清除按钮的当前事件,并双击设计器事件文本框,以便VS或Blend生成所有必要的代码以进行正确的订阅。

我已经基于您的代码here创建了一个示例。随意下载并查看,看看是否可以找到任何不一致之处。

至于更好的实现方式,请查看经典的MVVM模式和MVVM Light Toolkit。使用此工具包,您可以拥有一个中央ViewModel类,它将处理所有按钮命令和绑定,而无需使用代码后台。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接