c# - 如何知道 child 添加到 StackPanel?

标签 c# wpf

检测 child 何时添加到 StackPanel 的有效方法是什么?我以 StackPanel 为例,它可以是 GridWrapPanel 或派生自 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/

相关文章:

wpf - WPF中的派生类和主题继承?

c# - 非字符串的 .net 本地化

c# - 为什么在 C# 中将静态类声明为密封的和抽象的?

c# - 如何在 Rx.Net 中使用异步累加器实现 ScanAsync 运算符?

c# - 合并 XPS 文件将打开的文件句柄留给文档引用

c# - 为什么在 oauth2 中缓存访问 token 被认为是不好的?

c# - 识别窗口实例是否已经打开

c# - 模型更改更新 View-Model WPF

WPF DataGrid 有 RowEditEnding 但没有 RowEditEnded

c# - 手电筒应用程序每次在 Windows Phone 中崩溃