WPF将UIElement替换为另一个
本文关键字:另一个 替换 UIElement WPF | 更新日期: 2023-09-27 17:57:57
如果我有
<StackPanel>
<Button name="btn"/>
</StackPanel>
当我按下btn
按钮时,如何将其替换为不同的控件?在这种情况下,我知道父级是StackPanel,所以我可以将父级强制转换为StackPanel,然后替换该子级。但如果我有边界呢?
<Border>
<Button name="btn"/>
</Border>
多亏了McGarnagle,我创建了这个扩展方法
在不事先知道按钮的父控件的情况下,如何用自定义控件替换按钮
编辑
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");
}
}
我想您可以循环浏览可能的基类。没有那么多:StackPanel
是Panel
,Border
是Decorator
,…
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;
}
所有容器都是Panel或ContentControl或UserControl。因此,您可以检查父控件是否继承自这些控件之一。
Yo可以获得Control
的逻辑父级,并使用运算符is
检查其类型,如下所示:
var parent = MyButton.Parent;
if (parent is StackPanel)
{
// do something with StackPanel
}
if (parent is Border)
{
// do something with Border
}