WinRT自定义控件依赖项属性设置/绑定

时间:2012-05-04 01:39:34

标签: binding custom-controls dependency-properties windows-runtime winrt-xaml

我正在尝试为WinRT / Metro应用程序开发自定义控件。

它有一个依赖属性,我希望能够在自定义控件中设置它的值。但是,使用SetValue会中断控件的使用者可能创建的任何绑定。

我找到的解决方案(例如SetCurrentValue)似乎都不适用于WinRT / Metro。这个问题有方法解决吗?

这听起来很简单 - 老实说! - 我试图在这里和其他地方找到解决方案。任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:2)

您可以在PropertyMetadata中设置默认值(Dr. WPF' s snippets以进行救援!)。

#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

编辑*

如果要更改值 - 可以,但是如果使用OneWay的基本绑定 - 即 - 它从绑定源获取值并将其设置为依赖项属性 - 绑定将停止工作,因为源和目标值不再同步。

如果设置Mode="TwoWay" - 绑定目标(您的控件)修改依赖项属性时将更新绑定源,因此绑定将保持有效并将继续双向工作。