Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WinRT Custom Control Dependency Property Setting/Binding

I'm trying develop a custom control for a WinRT/Metro application.

It has a dependency property and I would like to be able to set its value within the custom control. However, using SetValue breaks any bindings that consumers of the control may have created.

None of the solutions I've found (e.g. SetCurrentValue) seem to apply to WinRT/Metro. Is there a solution to this?

It sounds like a simple thing to do and - honestly! - I've tried to find a solution here and elsewhere. Any help would be greatly appreciated.

like image 669
Rich T Avatar asked Nov 05 '22 00:11

Rich T


1 Answers

You can set the default value in PropertyMetadata (Dr. WPF's snippets to the rescue!).

#region IsAvailable
private static bool DefaultIsAvailable = false;

/// <summary>
/// IsAvailable Dependency Property
/// </summary>
public static readonly DependencyProperty IsAvailableProperty =
    DependencyProperty.Register(
        "IsAvailable",
        typeof(bool),
        typeof(CustomControl1),
        new PropertyMetadata(DefaultIsAvailable, OnIsAvailableChanged));

/// <summary>
/// Gets or sets the IsAvailable property. This dependency property 
/// indicates ....
/// </summary>
public bool IsAvailable
{
    get { return (bool)GetValue(IsAvailableProperty); }
    set { SetValue(IsAvailableProperty, value); }
}

/// <summary>
/// Handles changes to the IsAvailable property.
/// </summary>
/// <param name="d">
/// The <see cref="DependencyObject"/> on which
/// the property has changed value.
/// </param>
/// <param name="e">
/// Event data that is issued by any event that
/// tracks changes to the effective value of this property.
/// </param>
private static void OnIsAvailableChanged(
    DependencyObject d, DependencyPropertyChangedEventArgs e)
{
    var target = (CustomControl1)d;
    bool oldIsAvailable = (bool)e.OldValue;
    bool newIsAvailable = target.IsAvailable;
    target.OnIsAvailableChanged(oldIsAvailable, newIsAvailable);
}

/// <summary>
/// Provides derived classes an opportunity to handle changes
/// to the IsAvailable property.
/// </summary>
/// <param name="oldIsAvailable">The old IsAvailable value</param>
/// <param name="newIsAvailable">The new IsAvailable value</param>
protected virtual void OnIsAvailableChanged(
    bool oldIsAvailable, bool newIsAvailable)
{
}
#endregion

EDIT*

If you want to change the value - you can, but if you use a basic binding that is OneWay - i.e. - it takes the value from a binding source and sets it to the dependency property - the binding will stop working because source and target values won't be synchronized any more.

If you set Mode="TwoWay" - the binding source will be updated when the binding target (your control) modifies the dependency property, so the binding will remain valid and will continue working both ways.

like image 94
Filip Skakun Avatar answered Nov 15 '22 07:11

Filip Skakun