2015-07-16 4 views
0

Возможно ли комбинировать несколько DrawingBrushes в одном или, альтернативно, есть способ назначить несколько Brushes моим Grid?WPF объединение нескольких DrawingBrush

<Grid Name="gridContainer" Background="{StaticResource GridTile, RectangeGridTile}"> 

Очевидно, что вышеуказанный код не сработает. Исходный код:

<DrawingBrush x:Key="GridTile" Viewport="0,0,4,16" ViewportUnits="Absolute" TileMode="Tile"> 
    <DrawingBrush.Drawing> 
     <DrawingGroup> 
      <GeometryDrawing Geometry="M0,0 L1,0 1,0.05, 0,0.05Z" Brush="Black" /> 
      <GeometryDrawing Geometry="M0,0 L0,1 0.1,1, 0.1,0Z"  Brush="Black" /> 
     </DrawingGroup> 
    </DrawingBrush.Drawing> 
</DrawingBrush> 

<DrawingBrush x:Key="RectangeGridTile" Viewport="0,0,120,48" ViewportUnits="Absolute" TileMode="Tile"> 
    <DrawingBrush.Drawing > 
     <DrawingGroup> 
      <GeometryDrawing Geometry="M0,0 L1,0 1,0.05, 0,0.05Z" Brush="Black" /> 
      <GeometryDrawing Geometry="M0,0 L0,1 0.1,1, 0.1,0Z"  Brush="Black" /> 
     </DrawingGroup> 
    </DrawingBrush.Drawing> 
</DrawingBrush> 
+0

Вы решили проблему? –

ответ

1

пользовательские кисти не поддерживаются в WPF (типа кисти являются internal и не может быть унаследован от), создавая таким образом кисть не представляется возможным.

Вы можете использовать MarkupExtension для моделирования поведения пользовательской кисти, которая позволяет использовать синтаксис XAML и предоставлять настраиваемое значение, которое позволяет использовать встроенный набор SolidColorBrush для значения, скажем, двух смешивание цветов:

/// <summary> 
/// Markup extension to mix two SolidColorBrushes together to produce a new SolidColorBrush. 
/// </summary> 
[MarkupExtensionReturnType(typeof(SolidColorBrush))] 
public class MixedColorBrush : MarkupExtension, INotifyPropertyChanged 
{ 
    /// <summary> 
    /// The foreground mix color; defaults to white. 
    /// If not changed, the result will always be white. 
    /// </summary> 
    private SolidColorBrush foreground = Brushes.White; 

    /// <summary> 
    /// The background mix color; defaults to black. 
    /// If not set, the result will be the foreground color. 
    /// </summary> 
    private SolidColorBrush background = Brushes.Black; 

    /// <summary> 
    /// PropertyChanged event for WPF binding. 
    /// </summary> 
    public event PropertyChangedEventHandler PropertyChanged; 

    /// <summary> 
    /// Gets or sets the foreground mix color. 
    /// </summary> 
    public SolidColorBrush Foreground 
    { 
     get 
     { 
      return this.foreground; 
     } 
     set 
     { 
      this.foreground = value; 
      this.NotifyPropertyChanged("Foreground"); 
     } 
    } 

    /// <summary> 
    /// Gets or sets the background mix color. 
    /// </summary> 
    public SolidColorBrush Background 
    { 
     get 
     { 
      return this.background; 
     } 
     set 
     { 
      this.background = value; 
      this.NotifyPropertyChanged("Background"); 
     } 
    } 

    /// <summary> 
    /// Returns a SolidColorBrush that is set as the value of the 
    /// target property for this markup extension. 
    /// </summary> 
    /// <param name="serviceProvider">Object that can provide services for the markup extension.</param> 
    /// <returns>The object value to set on the property where the extension is applied.</returns> 
    public override object ProvideValue(IServiceProvider serviceProvider) 
    { 
     if (this.foreground != null && this.background != null) 
     { 
      // Create a new brush as a composite of the old ones 
      // This does simple non-perceptual additive color, e.g 
      // blue + red = magenta, but you can swap in a different 
      // algorithm to do subtractive color (red + yellow = orange) 
      return new SolidColorBrush(this.foreground.Color + this.background.Color); 
     } 

     // If either of the brushes was set to null, return an empty (white) brush. 
     return new SolidColorBrush(); 
    } 

    /// <summary> 
    /// Raise the property changed event. 
    /// </summary> 
    /// <param name="propertyName">Name of the property which has changed.</param> 
    protected void NotifyPropertyChanged(string propertyName) 
    { 
     if (this.PropertyChanged != null) 
     { 
      this.PropertyChanged(this, new PropertyChangedEventArgs(propertyName)); 
     } 
    } 
} 

, которые затем могут быть использованы из XAML, как вы нормальный кисти:

<Grid> 
    <Grid.Background> 
     <local:MixedColorBrush Foreground="Blue" Background="Red"/> 
    </Grid.Background> 
</Grid> 

Или используя синтаксис расширения разметки:

<Grid Background="{local:MixedColorBrush Foreground=Blue, Background=Red}"> 

Примечание:

Вы не можете использовать DynamicResource или StaticResource ссылки для связывания значений других ресурсов в приложении. MarkupExtension не является объектом DependencyObject, а привязка ресурсов работает только с DependencyObjects; встроенные кисти - это DependencyObjects, поэтому привязка работает с традиционными кистями.