检测 child 何时添加到 StackPanel
的有效方法是什么?我以 StackPanel
为例,它可以是 Grid
、WrapPanel
或派生自 Panel 的任何控件。
我正在尝试以两种方式添加控件。使用 XAML 和 AttachedProperty 的 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>
在这里您可以看到在按钮“测试 1”之前添加了按钮“测试 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()
然后重新排序
关于c# - 如何知道 child 添加到 StackPanel?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17280836/