我有一个用户控件,其中在 Canvas 内包含一个椭圆。我在另一个窗口中使用此控件,当我设置背景颜色时,我只想更改椭圆的背景。如何更改椭圆(子)背景而不更改 Canvas (父)背景颜色?
最佳答案
<强>1。将 DependencyProperty
添加到 MyUserControl
的代码隐藏中。
请注意,Register
方法的第三个参数是您的 UserControl
的 Type
名称
public Brush EllipseFill
{
get { return (Brush)GetValue(EllipseFillProperty); }
set { SetValue(EllipseFillProperty, value); }
}
public static readonly DependencyProperty EllipseFillProperty =
DependencyProperty.Register("EllipseFill", typeof(Brush), typeof(MyUserControl), new PropertyMetadata(null));
<强>2。添加对定义 MyUserControl
的命名空间的主 Window
和 UserControl
的 xaml 文件的引用:
xmlns:local="clr-namespace:WpfApplication1"
<强>3。将 Ellipse
的 Fill
属性绑定(bind)到 MyUserControl
上定义的依赖属性。
请注意 RelativeSource
绑定(bind)的 AncestorType
参数中 MyUserControl
的使用。
<Viewbox>
<Canvas Width="100" Height="100">
<Ellipse Width="50"
Height="20"
Canvas.Top="50"
Canvas.Left="50"
Fill="{Binding Path=EllipseFill,
RelativeSource= {RelativeSource Mode=FindAncestor,
AncestorType={x:Type local:MyUserControl}}}"
/>
<Rectangle Width="20"
Height="40"
Canvas.Top="10"
Canvas.Left="10"
Fill="Blue"
/>
</Canvas>
</Viewbox>
<强>4。在主Window
MyUserControl
上设置EllipseFill
属性
<local:MyUserControl EllipseFill="Red"/>
关于wpf - 如何更改子控件xaml的背景颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36477129/