XamlCompositionBrushBase Classe

Definizione

Fornisce una classe di base usata per creare pennelli XAML che dipingono un'area con un oggetto CompositionBrush.

public ref class XamlCompositionBrushBase : Brush
/// [Windows.Foundation.Metadata.ContractVersion(Windows.Foundation.UniversalApiContract, 262144)]
/// [Windows.Foundation.Metadata.MarshalingBehavior(Windows.Foundation.Metadata.MarshalingType.Agile)]
/// [Windows.Foundation.Metadata.Threading(Windows.Foundation.Metadata.ThreadingModel.Both)]
class XamlCompositionBrushBase : Brush
[Windows.Foundation.Metadata.ContractVersion(typeof(Windows.Foundation.UniversalApiContract), 262144)]
[Windows.Foundation.Metadata.MarshalingBehavior(Windows.Foundation.Metadata.MarshalingType.Agile)]
[Windows.Foundation.Metadata.Threading(Windows.Foundation.Metadata.ThreadingModel.Both)]
public class XamlCompositionBrushBase : Brush
Public Class XamlCompositionBrushBase
Inherits Brush
Ereditarietà
Object Platform::Object IInspectable DependencyObject Brush XamlCompositionBrushBase
Derivato
Attributi

Requisiti Windows

Famiglia di dispositivi
Windows 10 Creators Update (è stato introdotto in 10.0.15063.0)
API contract
Windows.Foundation.UniversalApiContract (è stato introdotto in v4.0)

Esempio

In questo esempio viene illustrata la definizione di un pennello personalizzato che disegna una copia sfocata di qualsiasi cosa sia dietro un UIElement in cui viene applicato il pennello usando un effetto di sfocatura Win2D e un oggetto CompositionBackdropBrush:

public sealed class BackdropBlurBrush : XamlCompositionBrushBase
{
    public static readonly DependencyProperty BlurAmountProperty = DependencyProperty.Register(
        "BlurAmount",
        typeof(double),
        typeof(BackdropBlurBrush),
        new PropertyMetadata(0.0, new PropertyChangedCallback(OnBlurAmountChanged)
        )
    );

    public double BlurAmount
    {
        get { return (double)GetValue(BlurAmountProperty); }
        set { SetValue(BlurAmountProperty, value); }
    }

    private static void OnBlurAmountChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
    {
        var brush = (BackdropBlurBrush)d;
        // Unbox and set a new blur amount if the CompositionBrush exists.
        brush.CompositionBrush?.Properties.InsertScalar("Blur.BlurAmount", (float)(double)e.NewValue);            
    }

    public BackdropBlurBrush()
    {
    }

    protected override void OnConnected()
    {
        // Delay creating composition resources until they're required.
        if (CompositionBrush == null)
        {
            var backdrop = Window.Current.Compositor.CreateBackdropBrush();                

            // Use a Win2D blur affect applied to a CompositionBackdropBrush.
            var graphicsEffect = new GaussianBlurEffect
            {
                Name = "Blur",
                BlurAmount = (float)this.BlurAmount,
                Source = new CompositionEffectSourceParameter("backdrop")
            };

            var effectFactory = Window.Current.Compositor.CreateEffectFactory(graphicsEffect, new[] { "Blur.BlurAmount" });
            var effectBrush = effectFactory.CreateBrush();

            effectBrush.SetSourceParameter("backdrop", backdrop);

            CompositionBrush = effectBrush;
        }
    }

    protected override void OnDisconnected()
    {
        // Dispose of composition resources when no longer in use.
        if (CompositionBrush != null)
        {
            CompositionBrush.Dispose();
            CompositionBrush = null;
        }
    }
}
Public NotInheritable Class BackdropBlurBrush
    Inherits XamlCompositionBrushBase

    Public Shared ReadOnly BlurAmountProperty As DependencyProperty = DependencyProperty.Register(
            "BlurAmount",
            GetType(Double),
            GetType(BackdropBlurBrush),
            New PropertyMetadata(0.0, New PropertyChangedCallback(AddressOf OnBlurAmountChanged)
            )
        )

    Public Property BlurAmount As Double
        Get
            Return DirectCast(GetValue(BlurAmountProperty), Double)
        End Get
        Set
            SetValue(BlurAmountProperty, Value)
        End Set
    End Property

    Private Shared Sub OnBlurAmountChanged(d As DependencyObject, e As DependencyPropertyChangedEventArgs)
        Dim brush = DirectCast(d, BackdropBlurBrush)
        ' Unbox And set a New blur amount if the CompositionBrush exists.
        brush.CompositionBrush?.Properties.InsertScalar("Blur.BlurAmount", Convert.ToSingle(DirectCast(e.NewValue, Double)))
    End Sub

    Protected Overrides Sub OnConnected()
        If Me.CompositionBrush Is Nothing Then

            Dim backdrop As CompositionBackdropBrush = Window.Current.Compositor.CreateBackdropBrush()

            ' Use a Win2D blur affect applied to a CompositionBackdropBrush.
            Dim graphicsEffect As GaussianBlurEffect = New GaussianBlurEffect()
            graphicsEffect.Name = "Blur"
            graphicsEffect.BlurAmount = Me.BlurAmount
            graphicsEffect.Source = New CompositionEffectSourceParameter("backdrop")

            Dim effectFactory As CompositionEffectFactory = Window.Current.Compositor.CreateEffectFactory(graphicsEffect, New String() {"Blur.BlurAmount"})
            Dim effectBrush As CompositionEffectBrush = effectFactory.CreateBrush()

            effectBrush.SetSourceParameter("backdrop", backdrop)

            CompositionBrush = effectBrush
        End If
    End Sub

    Protected Overrides Sub OnDisconnected()
        ' Dispose of composition resources when no longer in use.
        If CompositionBrush IsNot Nothing Then
            CompositionBrush.Dispose()
            CompositionBrush = Nothing
        End If
    End Sub
End Class

Per l'esempio di codice C++/WinRT riportato di seguito, è necessario aggiungere un file Midl File (.idl) al progetto.

// BackdropBlurBrush.idl
namespace MyApp
{
    [default_interface]
    runtimeclass BackdropBlurBrush : Windows.UI.Xaml.Media.XamlCompositionBrushBase
    {
        BackdropBlurBrush();
        static Windows.UI.Xaml.DependencyProperty BlurAmountProperty{ get; };
        Double BlurAmount;
    }
}
// pch.h
// You'll need to install the Microsoft Win2D NuGet package for this code example.
#include <winrt/Microsoft.Graphics.Canvas.Effects.h>
#include <winrt/Windows.Graphics.Effects.h>

// BackdropBlurBrush.h.
struct BackdropBlurBrush : BackdropBlurBrushT<BackdropBlurBrush>
{
    BackdropBlurBrush() = default;

    static Windows::UI::Xaml::DependencyProperty BlurAmountProperty() { return m_blurAmountProperty; }

    double BlurAmount()
    {
        return winrt::unbox_value<double>(GetValue(m_blurAmountProperty));
    }

    void BlurAmount(double value)
    {
        SetValue(m_blurAmountProperty, winrt::box_value(value));
    }

    void OnConnected();
    void OnDisconnected();

    static void OnBlurAmountChanged(Windows::UI::Xaml::DependencyObject const& d, Windows::UI::Xaml::DependencyPropertyChangedEventArgs const& e);

private:
    static Windows::UI::Xaml::DependencyProperty m_blurAmountProperty;
};

// WindowBlurBrush.cpp.
Windows::UI::Xaml::DependencyProperty BackdropBlurBrush::m_blurAmountProperty =
    Windows::UI::Xaml::DependencyProperty::Register(
        L"BlurAmount",
        winrt::xaml_typename<double>(),
        winrt::xaml_typename<MyApp::BackdropBlurBrush>(),
        Windows::UI::Xaml::PropertyMetadata{ winrt::box_value(0.), Windows::UI::Xaml::PropertyChangedCallback{ &BackdropBlurBrush::OnBlurAmountChanged } }
);

void BackdropBlurBrush::OnBlurAmountChanged(Windows::UI::Xaml::DependencyObject const& d, Windows::UI::Xaml::DependencyPropertyChangedEventArgs const& e)
{
    auto brush{ d.as<MyApp::BackdropBlurBrush>() };
    // Unbox and set a new blur amount if the CompositionBrush exists.
    if (brush.CompositionBrush() != nullptr)
    {
        brush.CompositionBrush().Properties().InsertScalar(L"Blur.BlurAmount", (float)winrt::unbox_value<double>(e.NewValue()));
    }
}

void BackdropBlurBrush::OnConnected()
{
    // Delay creating composition resources until they're required.
    if (!CompositionBrush())
    {
        auto backdrop{ Windows::UI::Xaml::Window::Current().Compositor().CreateBackdropBrush() };

        // Use a Win2D blur affect applied to a CompositionBackdropBrush.
        Microsoft::Graphics::Canvas::Effects::GaussianBlurEffect graphicsEffect{};
        graphicsEffect.Name(L"Blur");
        graphicsEffect.BlurAmount(this->BlurAmount());
        graphicsEffect.Source(Windows::UI::Composition::CompositionEffectSourceParameter(L"backdrop"));

        auto effectFactory{ Windows::UI::Xaml::Window::Current().Compositor().CreateEffectFactory(graphicsEffect, { L"Blur.BlurAmount" }) };
        auto effectBrush{ effectFactory.CreateBrush() };

        effectBrush.SetSourceParameter(L"backdrop", backdrop);

        CompositionBrush(effectBrush);
    }
}

void BackdropBlurBrush::OnDisconnected()
{
    // Dispose of composition resources when no longer in use.
    if (CompositionBrush())
    {
        CompositionBrush(nullptr);
    }
}
// WindowBlurBrush.h:
public ref class BackdropBlurBrush sealed :
    public Windows::UI::Xaml::Media::XamlCompositionBrushBase
{
public:
    BackdropBlurBrush();

    static property Windows::UI::Xaml::DependencyProperty^ BlurAmountProperty
    {
        Windows::UI::Xaml::DependencyProperty^ get() { return m_blurAmountProperty; }
    };

    property double BlurAmount
    {
        double get() 
        {
            return static_cast<double>(GetValue(BlurAmountProperty));
        }
        void set(double value) 
        {
            SetValue(BlurAmountProperty, value);
        }
    };

protected:
    virtual void OnConnected() override;
    virtual void OnDisconnected() override;	
    private:
    static Windows::UI::Xaml::DependencyProperty^ m_blurAmountProperty;
    static void OnBlurAmountChanged(Windows::UI::Xaml::DependencyObject^ d, Windows::UI::Xaml::DependencyPropertyChangedEventArgs^ e);
};

// WindowBlurBrush.cpp:
DependencyProperty^ BackdropBlurBrush::m_blurAmountProperty = DependencyProperty::Register(
    "BlurAmount",
    Platform::String::typeid,
    BackdropBlurBrush::typeid,
    ref new PropertyMetadata(0.0, ref new PropertyChangedCallback(OnBlurAmountChanged))
);

BackdropBlurBrush::BackdropBlurBrush()
{
}

void BackdropBlurBrush::OnBlurAmountChanged(DependencyObject^ d, DependencyPropertyChangedEventArgs^ e)
{
    auto brush = static_cast<BackdropBlurBrush^>(d);
    // Unbox and set a new blur amount if the CompositionBrush exists
    if (brush->CompositionBrush != nullptr)
    {
        brush->CompositionBrush->Properties->InsertScalar("Blur.BlurAmount", (float)static_cast<double>(e->NewValue));
    }
}

void BackdropBlurBrush::OnConnected()
{
    // Delay creating composition resources until they're required
    if (CompositionBrush == nullptr)
    {
        auto backdrop = Window::Current->Compositor->CreateBackdropBrush();

        // Use a Win2D blur affect applied to a CompositionBackdropBrush
        auto graphicsEffect = ref new GaussianBlurEffect();
        graphicsEffect->Name = "Blur";
        graphicsEffect->BlurAmount = static_cast<float>(this->BlurAmount);
        graphicsEffect->Source = ref new CompositionEffectSourceParameter("backdrop");

        auto animatableProperties = ref new Platform::Collections::Vector<Platform::String^>();
        animatableProperties->Append("Blur.BlurAmount");

        auto effectFactory = Window::Current->Compositor->CreateEffectFactory(graphicsEffect, animatableProperties);
        auto effectBrush = effectFactory->CreateBrush();

        effectBrush->SetSourceParameter("backdrop", backdrop);

        CompositionBrush = effectBrush;
    }
}

void BackdropBlurBrush::OnDisconnected()
{
    // Dispose of composition resources when no longer in use
    if (CompositionBrush != nullptr)
    {
        delete CompositionBrush;
        CompositionBrush = nullptr;
    }
}

Il pennello precedente può quindi essere usato come qualsiasi altro tipo di pennello XAML per disegnare UIElements, ad esempio:

Per C++/WinRT, aggiungere #include "BackdropBlurBrush.h" anche a MainPage.h.

<Ellipse Width="100" Height="100">
    <Ellipse.Fill>
        <local:BackdropBlurBrush BlurAmount="10" />
    </Ellipse.Fill>
</Ellipse>

Commenti

È possibile usare XamlCompositionBrushBase per creare pennelli personalizzati.

Ad esempio, può essere usato per creare un pennello che applica effetti a UIElement XAML usando un oggetto CompositionEffectBrush o un Oggetto SceneLightingEffect che controlla le proprietà riflettenti degli elementi quando viene acceso da un XamlLight o un'intera serie di effetti concatenati insieme per produrre qualcosa di più complesso.

Quando si crea un pennello, in genere è consigliabile ritardare la creazione di un oggetto CompositionBrush e qualsiasi risorsa correlata fino a quando non viene usato il pennello. Il metodo OnConnected viene chiamato quando un pennello viene usato per la prima volta sullo schermo per disegnare un elemento, quindi è possibile eseguire l'override di OnConnected per creare in modo sicuro le risorse solo quando sono necessarie. Ciò significa che è possibile creare un'istanza di un pennello in un resourceDictionary, quindi fare riferimento alla risorsa pennello successivamente da altre parti delle definizioni dell'interfaccia utente e pagare solo il costo della creazione di risorse di composizione quando il pennello è effettivamente in uso.

È anche consigliabile eliminare le risorse di composizione quando non sono più in uso. Il metodo OnDisconnected viene chiamato quando un'istanza del pennello non è più in uso ovunque sullo schermo, quindi è possibile eseguire l'override di OnDisconnected per eliminare in modo sicuro le risorse. Se il pennello viene usato di nuovo dopo essere stato disconnesso, Verrà chiamato di nuovo OnConnected .

Costruttori

XamlCompositionBrushBase()

Fornisce il comportamento di inizializzazione della classe di base per le classi derivate xamlCompositionBrushBase .

Proprietà

CompositionBrush

Ottiene o imposta l'oggetto CompositionBrush usato da questo pennello XAML.

Dispatcher

Ottiene CoreDispatcher associato a questo oggetto. CoreDispatcher rappresenta una struttura che può accedere a DependencyObject nel thread dell'interfaccia utente anche se il codice viene avviato da un thread non interfaccia utente.

(Ereditato da DependencyObject)
FallbackColor

Colore da usare per il rendering nel caso in cui il rendering di CompositionBrush non possa essere eseguito.

FallbackColorProperty

Identifica la proprietà di dipendenza FallbackColor .

Opacity

Ottiene o imposta il grado di opacità di un pennello.

(Ereditato da Brush)
RelativeTransform

Ottiene o imposta la trasformazione applicata al pennello usando coordinate relative.

(Ereditato da Brush)
Transform

Ottiene o imposta la trasformazione applicata al pennello.

(Ereditato da Brush)

Metodi

ClearValue(DependencyProperty)

Cancella il valore locale di una proprietà di dipendenza.

(Ereditato da DependencyObject)
GetAnimationBaseValue(DependencyProperty)

Restituisce qualsiasi valore di base stabilito per una proprietà di dipendenza, che si applica nei casi in cui un'animazione non è attiva.

(Ereditato da DependencyObject)
GetValue(DependencyProperty)

Restituisce il valore effettivo corrente di una proprietà di dipendenza da un oggetto DependencyObject.

(Ereditato da DependencyObject)
OnConnected()

Richiamato quando un pennello viene usato per la prima volta sullo schermo per disegnare un elemento.

Quando implementato in una classe derivata, è possibile creare un'istanza di CompositionBrush e specificarla nel framework impostando la proprietà CompositionBrush .

OnDisconnected verrà chiamato quando il pennello non viene più usato per disegnare gli elementi.

OnDisconnected()

Richiamato quando il pennello non viene più usato per disegnare elementi.

Quando implementato in una classe derivata, è possibile eliminare in modo sicuro il pennello compostione e altre risorse di composizione.

OnConnected verrà chiamato di nuovo se il pennello viene usato successivamente per disegnare eventuali elementi dopo la disconnessione.

PopulatePropertyInfo(String, AnimationPropertyInfo)

Definisce una proprietà che può essere animata.

(Ereditato da Brush)
PopulatePropertyInfoOverride(String, AnimationPropertyInfo)

Quando sottoposto a override in una classe derivata, definisce una proprietà che può essere animata.

(Ereditato da Brush)
ReadLocalValue(DependencyProperty)

Restituisce il valore locale di una proprietà di dipendenza, se viene impostato un valore locale.

(Ereditato da DependencyObject)
RegisterPropertyChangedCallback(DependencyProperty, DependencyPropertyChangedCallback)

Registra una funzione di notifica per l'ascolto delle modifiche a un'istanza di DependencyObject specifica.

(Ereditato da DependencyObject)
SetValue(DependencyProperty, Object)

Imposta il valore locale di una proprietà di dipendenza in un oggetto DependencyObject.

(Ereditato da DependencyObject)
UnregisterPropertyChangedCallback(DependencyProperty, Int64)

Annulla una notifica di modifica registrata in precedenza chiamando RegisterPropertyChangedCallback.

(Ereditato da DependencyObject)

Si applica a

Vedi anche