我看到了一些帖子谈论如何在运行时删除已添加的UserControl,但我的问题有点不同。 我有一个UserControl,它由一个带有小“x”按钮的图像组成,该按钮位于右上角,用于从其父级画布中删除自身(UserControl)。 还要注意的是,当用户双击ListboxItem时,在运行时添加了UserControl。 我为右上角按钮编写了Click事件处理程序,但此代码根本未运行。 我知道这是因为我在这个代码中设置了断点,而当我单击按钮时,断点没有被触发。
所以:
1.为什么移除按钮的单击事件没有被处理?
2.也许有更好的实现方式,请给予建议。
下面是用于添加的代码:
以下是UserControl的cs代码:
XAML代码如下:
所以:
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
e.OriginalSource.GetType() == typeof(Border)
或者e.OriginalSource is Border
的形式(这应该允许子类)。 - H.B.