我想创建一个用户控件,它的工作方式与经典的Panel(或Canvas)控件相同,我希望有一些用户无法删除的默认按钮。
我试过了:
namespace WpfApplication1
{
public class CustomPanel : Canvas
{
public CustomPanel()
{
Button b = new Button();
b.Name = "Button1";
b.Content = "Button1";
this.Children.Add(b);
}
}
}
它可以工作,但是当我编译它并在设计器中创建一个CustomPanel实例然后尝试插入另一个项时,在构造函数中创建的Button被删除。
这是正确的方法还是有更好的(更有效/更优雅)的方式然后修改构造函数?
提前感谢任何努力。
答案 0 :(得分:2)
您的问题是您在构造函数中将Button添加到 Children 对象,然后在XAML中实例化时替换整个 Children 对象。 我猜你的XAML看起来像这样:?
<wpfApplication3:CustomPanel>
<Button Content="New b"/>
</wpfApplication3:CustomPanel>
如果你这样开始,你会看到按钮保持原位。
public MainWindow()
{
InitializeComponent();
Loaded += OnLoaded;
}
private void OnLoaded(object sender, RoutedEventArgs routedEventArgs)
{
CustomPanel p = new CustomPanel();
p.Children.Add(new Button(){Content = "T"});
gr.Children.Add(p);
}
你可以做些什么来避免这种情况:
public CustomPanel()
{
Initialized += OnInitialized;
}
private void OnInitialized(object sender, EventArgs eventArgs)
{
var b = new Button { Name = "Button1", Content = "Button1" };
Children.Insert(0,b);
}
现在,在添加按钮之前,等到XAML替换了Children对象。