当Canvas位于VisualBrush内部时,其背景会被忽略。

4

给定以下的XAML代码:

<Style TargetType="PasswordBox">
    <Setter Property="Background">
        <Setter.Value>
            <VisualBrush TileMode="Tile"
                         Viewport="0,0,10,10" ViewportUnits="Absolute">
                <VisualBrush.Visual>
                    <Canvas Background="{x:Static SystemColors.WindowBrush}">
                        <Path Data="M0,0 L10,10 M0,10 L10,0">
                            <Path.Stroke>
                                <SolidColorBrush Color="{x:Static SystemColors.HighlightColor}"/>
                            </Path.Stroke>
                        </Path>
                    </Canvas>
                </VisualBrush.Visual>
            </VisualBrush>
        </Setter.Value>
    </Setter>
    ...

canvas的背景被忽略了,相反路径是可见的,而且背景是透明的,这是因为PasswordBox后面的表格。那么我应该在哪里设置“背景背景”?

我想设为 WindowBrush 会使它与背景窗体相同。你确定它不只是相同的颜色吗?你尝试过像 Background="Red" 这样的东西吗? - Jay
WindowBrush计算为不透明的颜色。红色也被忽略。 - Reinderien
把那个画笔设置在 Path.Fill 上怎么样? - Jay
刚试了一下,它也被忽略并且透明。 - Reinderien
1个回答

4
问题在于Canvas没有大小。
将其更改为以下内容,您应该能够看到它:
<Canvas Background="{x:Static SystemColors.WindowBrush}"
        Width="10"
        Height="10">

为了减少对这些维度的引用次数,您可以将它们声明为资源。由于您正在处理正方形,因此可以将其缩减为一个值:

    <Grid.Resources>
        <System:Double x:Key="Width">10</System:Double>
        <System:Double x:Key="Height">10</System:Double>
        <Style TargetType="PasswordBox">
            <Setter Property="Background">
                <Setter.Value>
                    <VisualBrush TileMode="Tile"
                                 ViewportUnits="Absolute">
                        <VisualBrush.Viewport>
                            <Rect Width="{StaticResource Width}"
                                  Height="{StaticResource Height}" />
                        </VisualBrush.Viewport>
                        <VisualBrush.Visual>
                            <Canvas Background="{x:Static SystemColors.WindowBrush}" 
                                    Width="{StaticResource Width}"
                                    Height="{StaticResource Height}" >

当然,如果你绑定到视图模型,你也可以通过绑定来驱动尺寸。

运行得非常好。但是,我的下一个问题是 - 我如何尽可能地消除对“10”的引用?我是否可以使用相对单位,并在(例如)视口之外的所有地方都写上“1”? - Reinderien

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接