Wpf 自定义面板在XAML设计器中无法正确渲染
我制作了一个自定义面板,其中包含一个扩展器,它有一个Stackpanel,可以在其中对它的直接子级进行排序,而不是在面板的子级中进行排序。但是,设计器拒绝渲染直接子对象(扩展器)的任何子对象 是否还需要做一些其他事情,使布局无效,以便设计师注意到其中有一些东西Wpf 自定义面板在XAML设计器中无法正确渲染,wpf,xaml,designer,Wpf,Xaml,Designer,我制作了一个自定义面板,其中包含一个扩展器,它有一个Stackpanel,可以在其中对它的直接子级进行排序,而不是在面板的子级中进行排序。但是,设计器拒绝渲染直接子对象(扩展器)的任何子对象 是否还需要做一些其他事情,使布局无效,以便设计师注意到其中有一些东西 public class ExpanderPanel : Panel { const double leftMargin = 24.0; private Expander _expander; public s
public class ExpanderPanel : Panel
{
const double leftMargin = 24.0;
private Expander _expander;
public string Header
{
get { return (string)GetValue(HeaderProperty); }
set { SetValue(HeaderProperty, value); }
}
public static readonly DependencyProperty HeaderProperty =
DependencyProperty.Register("Header", typeof(string), typeof(ExpanderPanel), new FrameworkPropertyMetadata(string.Empty, (d, e) =>
{
var panel = d as ExpanderPanel;
panel._expander.Header = panel.Header;
}));
public bool IsExpanded
{
get { return (bool)GetValue(IsExpandedProperty); }
set { SetValue(IsExpandedProperty, value); }
}
public static readonly DependencyProperty IsExpandedProperty =
DependencyProperty.Register("IsExpanded", typeof(bool), typeof(ExpanderPanel), new FrameworkPropertyMetadata(true, (d, e) =>
{
var panel = d as ExpanderPanel;
panel._expander.IsExpanded = panel.IsExpanded;
}));
public ExpanderPanel()
{
_expander = new Expander()
{
Content = new StackPanel()
{
HorizontalAlignment = HorizontalAlignment.Stretch,
Margin = new Thickness(leftMargin - 2, 0, 0, 0) // The Margin - 2 for borders... Don't know a better way...
},
HorizontalAlignment = HorizontalAlignment.Stretch,
};
Children.Add(_expander);
}
private void InitializePanel()
{
_expander.Header = Header;
_expander.Width = Width;
_expander.IsExpanded = IsExpanded;
var sp = _expander.Content as StackPanel;
while (InternalChildren.Count > 1)
{
var child = InternalChildren[1];
InternalChildren.RemoveAt(1);
sp.Children.Add(child);
}
}
public override void EndInit()
{
base.EndInit();
InitializePanel();
}
protected override Size MeasureOverride(Size availableSize)
{
var size = new Size();
_expander.Width = availableSize.Width;
_expander.Measure(availableSize);
size.Width = leftMargin + _expander.DesiredSize.Width;
if (size.Width > availableSize.Width)
{
size.Width = availableSize.Width;
}
size.Height += _expander.DesiredSize.Height;
return size;
}
protected override Size ArrangeOverride(Size finalSize)
{
var location = new Point();
_expander.Arrange(new Rect(location, _expander.DesiredSize));
return finalSize;
}
}
最后,我自己通过类中的日志记录找到了答案:当通过设计器运行时,永远不会调用构造函数。因此没有创建扩展器,我假设会发生一些NullReferenceException
我不明白的是为什么构造函数没有被调用。将逻辑放入事件处理程序调用的Initialize方法中的构造函数中进行修复。最终通过从类中进行日志记录找到了答案:当运行设计器时,永远不会调用构造函数。因此没有创建扩展器,我假设会发生一些NullReferenceException 我不明白的是为什么构造函数没有被调用。通过将逻辑放在事件处理程序调用的Initialize方法的构造函数中进行修复