WPF用另一个替换UIElement

时间:2014-04-10 17:35:56

标签: c# wpf

如果我有

<StackPanel>
    <Button name="btn"/>
</StackPanel>

当我按下该按钮时,如何将Button btn替换为其他控件?在这种情况下,我知道父对象是StackPanel,所以我可以将父对象转换为stackPanel,然后替换该子对象。但是如果我有边框怎么办?

<Border>
    <Button name="btn"/>
</Border>

感谢McGarnagle,我创建了这个扩展方法

如何在不事先知道按钮的父级的情况下用自定义控件替换Button?

修改

    public static void ReplaceWith(this FrameworkElement elementToReplace, FrameworkElement newControl)
    {
        newControl.Width = elementToReplace.Width;
        newControl.Height = elementToReplace.Height;
        newControl.Margin = elementToReplace.Margin;

        // get parent of control
        var parent = elementToReplace.Parent;

        if (parent is Panel)
        {
            var panel = (Panel)parent;

            for (var i = 0; i < panel.Children.Count; i++)
            {
                if (panel.Children[i] == elementToReplace)
                {
                    panel.Children.RemoveAt(i);
                    panel.Children.Insert(i, newControl);
                    break;
                }
            }
        }
        else if (parent is Decorator)
        {
            ((Decorator)parent).Child = newControl;
        }
        else if (parent is ContentControl)
        {
            ((ContentControl)parent).Content = newControl;
        }
        else
        {
            if(Debugger.IsAttached)
                Debugger.Break();

            throw new NotImplementedException("Missing other possibilities to implement");
        }
    }

3 个答案:

答案 0 :(得分:5)

我想你可以遍历可能的基类。没有那么多:StackPanelPanelBorderDecorator,...

var parent = btn.Parent;
var replacement = new TextBlock { Text = "replacement" };
if (parent is Panel)
{ 
    var panel = (Panel)parent;
    panel.Children.Remove(btn);
    panel.Children.Add(replacement);
}
else if (parent is Decorator)
{ 
    ((Decorator)parent).Child = replacement;
}
else if (parent is ContentControl)
{
    ((ContentControl)parent).Content = replacement;
}

答案 1 :(得分:1)

Yo可以获取Control逻辑父级,并使用运算符is检查其类型:

var parent = MyButton.Parent;

if (parent is StackPanel)
{ 
    // do something with StackPanel
}

if (parent is Border) 
{
    // do something with Border
}

答案 2 :(得分:1)

所有容器都是Panel或ContentControl或UserControl。因此,您可以检查父项是否从其中一个控件继承。