我使用简单的button_click回调函数实现了一个usercontrol。 此外,我实现了一个DP,它将StackPanel与图像设置为按钮的内容。 当我在没有DP的情况下使用usercontrol时,button_click工作正常,但是当我使用DP时,不再调用button_click回调函数... 谁知道为什么会这样?以及如何解决它? **我知道我可以通过许多其他方式实现设置图像,但我想坚持使用这种方法(这个项目只是对其他项目的研究)
用户控制xaml:
<UserControl x:Class="WpfApplication1.ButtonClick"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
mc:Ignorable="d"
d:DesignHeight="300" d:DesignWidth="300">
<Grid>
<Button Width="50" Height="40" Background="Transparent" BorderThickness="0" BorderBrush="Transparent" Click="Button_Click"></Button>
</Grid>
</UserControl>
cs用户控制文件:
public partial class ButtonClick : UserControl
{
public static readonly DependencyProperty ShowImageDP = DependencyProperty.Register("ShowImage", typeof(string), typeof(ButtonClick), new PropertyMetadata(null, new PropertyChangedCallback(SetImage)));
private string m_strSourceImage = string.Empty;
private BitmapImage m_oImage = null;
public ButtonClick()
{
InitializeComponent();
}
public string ShowImage
{
get
{
return (string)GetValue(ShowImageDP);
}
set
{
SetValue(ShowImageDP, value);
}
}
private static void SetImage(DependencyObject obj, DependencyPropertyChangedEventArgs args)
{
//Amit: Recive the path string to the Image file.
ButtonClick l_oBC = (ButtonClick)obj;
l_oBC.m_strSourceImage = (string)args.NewValue;
//Amit: If the file exsit read it to BitmapImage.
if (File.Exists(l_oBC.m_strSourceImage ))
{
l_oBC.m_oImage = new BitmapImage(new Uri(l_oBC.m_strSourceImage, UriKind.Absolute));
}
//Amit: Build an Image object out of the BitmapImage, set the image to a stack panle and set the panle to the button's content.
Image l_oImage = new Image();
l_oImage.Source = l_oBC.m_oImage;
StackPanel l_oPanle = new StackPanel();
l_oPanle.Orientation = Orientation.Horizontal;
l_oPanle.Children.Add(l_oImage);
l_oBC.Content = l_oPanle;
}
private void Button_Click(object sender, RoutedEventArgs e)
{
MessageBox.Show("We just clicked!");
}
}
答案 0 :(得分:1)
问题是您设置了整个usercontrol的内容而不仅仅是按钮。因此按钮完全从窗口中移除。
所以,如果你给这个按钮命名如下:
<Button x:Name="btn" Width="50" Height="40"...
..您应该可以像这样在DP中设置内容:
l_oBC.btn.Content = l_oPanle;