5

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

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

我发现的所有解决方案(例如 SetCurrentValue)似乎都不适用于 WinRT/Metro。有针对这个的解决方法吗?

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

4

1 回答 1

2

您可以在 PropertyMetadata 中设置默认值(WPF 博士的代码片段来拯救!)。

#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"- 当绑定目标(您的控件)修改依赖属性时,绑定源将被更新,因此绑定将保持有效并继续双向工作。

于 2012-05-04T05:30:10.437 回答