Jak ustawić DependencyProperty?
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.