Dependency property
Apparence
Définition
Etend une propriété pour qu'elle puisse être définie avec:
- un data binding
- un style
- un trigger
- un behavior
- un visual state
- une animation
Toutes les propriétés des control WPF sont des dependency properties.
Code
public string Text
{
get => (string)GetValue(TextProperty);
set => SetValue(TextProperty, value);
}
public static readonly DependencyProperty TextProperty = DependencyProperty.Register(
nameof(Text), // le nom de la propriété
typeof(string), // le type de la propriété
typeof(MyControl), // le type de la classe contenant la DependencyProperty
// la PropertyMetadata
new FrameworkPropertyMetadata(
String.Empty, // la valeur par défaut
FrameworkPropertyMetadataOptions.BindsTwoWayByDefault, // options
MyControl.OnTextChanged)); // change handler, appelé à chaque changement de valeur de la propriété
private static void OnTextChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
var myControl = (MyControl)d;
var oldValue = (string)e.OldValue;
var newValue = (string)e.NewValue;
myControl.OnTextChanged(oldValue, newValue);
}
protected virtual OnTextChanged(string oldValue, string newValue)
{
...
}
|
snippet propdp
public int MyProperty
{
get { return (int)GetValue(MyPropertyProperty); }
set { SetValue(MyPropertyProperty, value); }
}
public static readonly DependencyProperty MyPropertyProperty =
DependencyProperty.Register(
"MyProperty",
typeof(int),
typeof(ownerclass),
new PropertyMetadata(0)); // default value
|
PropertyMetadata, UIPropertyMetadata, FrameworkPropertyMetadata
Il y a une relation d'héritage entre ces 3 classes : PropertyMetadata ← UIPropertyMetadata ← FrameworkPropertyMetadata
- PropertyMetadata : base
- UIPropertyMetadata : permet de définir bool isAnimationProhibited
- FrameworkPropertyMetadata : permet de définir des FrameworkPropertyMetadataOptions et un UpdateSourceTrigger
Ajout d'une DependencyProperty BindableSource sur le WebBrowser
namespace Mon.Namespace
{
public static class WebBrowserUtility
{
public static readonly DependencyProperty BindableSourceProperty =
DependencyProperty.RegisterAttached("BindableSource",
typeof(string),
typeof(WebBrowserUtility),
new UIPropertyMetadata(null, BindableSourcePropertyChanged));
public static string GetBindableSource(DependencyObject obj)
{
return (string)obj.GetValue(BindableSourceProperty);
}
public static void SetBindableSource(DependencyObject obj, string value)
{
obj.SetValue(BindableSourceProperty, value);
}
public static void BindableSourcePropertyChanged(DependencyObject o, DependencyPropertyChangedEventArgs e)
{
WebBrowser browser = o as WebBrowser;
if (browser != null)
{
string uri = e.NewValue as string;
browser.Source = !String.IsNullOrEmpty(uri) ? new Uri(uri) : null;
}
}
}
|
<Window xmlns:ns="clr-namespace:Mon.Namespace"
<WebBrowser ns:WebBrowserUtility.BindableSource="{Binding Path=MaPropriété}"/>
|