Przygody z oprogramowaniem
  • Start
  • Szkolenia
    • Szkolenia otwarte
    • Katalog szkoleń
  • Usługi
    • Konsulting
    • Mentoring
    • Research & Development
  • Blog
  • Wiedza
    • Strefa wiedzy
    • BFsharp
    • SaaS
  • Klienci
  • Kontakt
0

Jak ustawić DependencyProperty?

13 December, 2011-C#, Silverlight, WPF

Jak ustawić DependencyProperty programowo? Otóz odpowiedź na to pytanie wydaje się bardzo prosta – użyć funkcji SetValue:

public void SetValue( DependencyProperty dp, Object value )

Niestety wymaganiem jest tu posiadanie instancji DependencyProperty.
Co jednak jeśli chcemy ustawić property znając tylko jego ścieżkę, np. “RenderTransform.Children[0].Angle”. By poradzić sobie z tym problemem można skorzystać z poniższej klasy.

public static class DependencyPropertyHelper
{
    private static readonly DependencyProperty DummyProperty = 
        DependencyProperty.RegisterAttached( "Dummy",
            typeof(Object), typeof(DependencyObject),
            new UIPropertyMetadata(null));

    private static readonly DependencyObject _object =
        new DependencyObject();

    public static void SetValue(object container,
        string dependencyProperty, object value)
    {
        Binding binding = new Binding(dependencyProperty) 
            { Source = container, Mode = BindingMode.TwoWay };

        BindingOperations.SetBinding(_object, DummyProperty, binding);
        _object.SetValue(DummyProperty, value);
#if SL
        BindingOperations.SetBinding(_object, DummyProperty, null);
#elif WPF
        BindingOperations.ClearBinding(_object, DummyProperty);
#endif
    }

    public static object GetValue(object container,
        string dependencyProperty)
    {
        Binding binding = new Binding(dependencyProperty) 
            { Source = container };
        BindingOperations.SetBinding(_object, DummyProperty, binding);

        return _object.GetValue(DummyProperty);
    }
}

Wykorzystuje ona pewien trick – używa bindingu do pobierania i ustawiania property.

Czytaj dalej | Dyskutuj

Kategorie

Architecture BFsharp Blog Business Framework C# CqRS DDD Debugging DSL EntityFramework Formula JavaScript Linq NHibernate SaaS Silverlight SQL Visual Studio WPF Wzorce

O mnie


RSS Feed

© macmichal.pl 2011 Wszystkie prawa zastrzeżone