浅谈WPF的VisualBrush

    首先看看VisualBrush的解释,msdn上面的解释是使用 Visual 绘制区域,那么我们再来看看什么是Visual呢?官方的解释是:获取或设置画笔的内容,Visual 是直接继承自DependencyObject,UIElement也是直接继承自Visual,我们常见的控件都是继承自Visual,Visual可以实现动态绑定,比如我们可以在代码中这样写: <VisualBrush Visual="{Binding TodayPeriod}" Stretch="Fill"></VisualBrush> 这样我们就可以把一个继承自Visual的控件(此处为TodayPeriod的一个UserControl)通过绑定的方式绑定到Visual中,我们再来看看VisualBrush这个类,首先来看一段示例代码:

                         <Border Grid.Column="1">
                                <Border.Background>
                                    <VisualBrush Stretch="Uniform">
                                        <VisualBrush.Visual>
                                            <Ellipse Fill="#003769" Opacity="0.6" Stretch="Fill" HorizontalAlignment="Stretch" VerticalAlignment="Stretch"                                                Width="100" Height="100"></Ellipse>
                                        </VisualBrush.Visual>
                                    </VisualBrush>
                                </Border.Background>
                                <StackPanel Orientation="Vertical" HorizontalAlignment="Center" VerticalAlignment="Center">
                                    <TextBlock FontSize="120" Text="{Binding SuccessError.Total,RelativeSource={RelativeSource TemplatedParent}}" Horizont                                         alAlignment="Center" VerticalAlignment="Center" Margin="0 0 0 -10"></TextBlock>
                                    <TextBlock FontSize="40" Text="总数" HorizontalAlignment="Center" VerticalAlignment="Center" Margin="0 -10 0 0">
</TextBlock> </StackPanel> </Border>

  这段代码是设置Border的Background为一个Ellipse,然后再在这个Ellipse上面放置两个TextBlock控件,本质上Background属性属于Brush类型,而我们的VisualBrush刚好继承自这个类型,我们来看一看VisualBrush的继承关系:

                                                                               System.Object

                                                                               System.Windows.Threading.DispatcherObject

                                                                               System.Windows.DependencyObject

                                                                               System.Windows.Freezable

 System.Windows.Media.Animation.Animatable

                                                                              System.Windows.Media.Brush

                                                                              System.Windows.Media.TileBrush
                                                                              System.Windows.Media.VisualBrush

所以在上面的代码中我们可以设置Border的Background为VisualBrush,我们在很多地方都是可以使用VisualBrush的,这里需要我们平时在使用的时候不断去反思去总结。

 

原文地址:https://www.cnblogs.com/seekdream/p/5239149.html