检测子项何时添加到StackPanel的有效方法是什么?我使用StackPanel作为示例,它可以是Grid,WrapPanel或任何派生自Panel的控件.
我试图以两种方式添加控件.使用AttachedProperty的XAML和PropertyChanged.
这是一些代码:
public class Region : UserControl
{
public static readonly DependencyProperty RegionNameProperty;
static Region()
{
RegionNameProperty = DependencyProperty.RegisterAttached(
"RegionName",
typeof(string),
typeof(Region),
new UIPropertyMetadata(new PropertyChangedCallback((s,e)=>
{
if(s is StackPanel)
{
StackPanel stack = (StackPanel)s;
stack.Children.Add(new Button(){Content="Test2"});
}
}))
);
}
}
XAML:
<StackPanel Name="stack2" local:Region.RegionName="MyRegion1">
<Button Content="Test 1"/>
</StackPanel>
在这里,您可以看到按钮“Test 1”之前添加了“Test 2”按钮.
谢谢,
最佳答案
I am adding two buttons to stackpanel.
1) from attached property changed – button “Test 2”
2) from XAML – button “Test 1”.
The problem: button “Test 2” is added before “Test 1”.
所有控件都在构造函数中创建“InitializeComponent”方法(我假设),因此您可以在Window.Loaded事件中进行重新排序.
xaml的按钮只创建一次,因此在Loaded事件中另外一个重新排序应该会有所帮助.
老答案:
有一个事件LayoutUpdated,您可以尝试这个,更多信息在这里:
http://msdn.microsoft.com/en-us/library/system.windows.uielement.layoutupdated.aspx
I am adding some controls on Setter of the attached property. I think Setter of the attached property is fired before the controls added on XAML. I need to know when controls added by XAML and reorder them
也许在添加子项后,您应该只调用StackPanel.UpdateLayout()然后重新排序