【发布时间】:2015-09-02 06:40:24
【问题描述】:
我有一个使用IsEnabled 绑定的应用程序。
我还需要暂时删除此绑定。
我创建了一个带有附加属性的ControlBehavior,用作临时存储位置。 ClearIsEnabledBinding 将设置此附加属性中使用的绑定。 RestoreIsEnabeldBinding 应该将绑定返回到原始位置。这行不通。当绑定被清除时,附加的属性也被清除。
场景是这样的。我有一个带有 IsEnabled 绑定到带有转换器的视图模型的文本框。当我使用特定函数时,无论视图模型中的值如何,所有 IsEnabled 都应该为真。这很容易,只需删除绑定并设置为 true。但是当我从这个函数返回时,我需要使用转换器将绑定恢复到它与视图模型的原始绑定。所以我需要将整个绑定表达式保存在某个地方,然后将其“放回”
我的班级如下:
对我做错了什么有什么建议吗?
public partial class ControlBehavior
{
public static readonly DependencyProperty IsEnabledBindingProperty = DependencyProperty.RegisterAttached(
"IsEnabledBinding",
typeof(BindingExpression),
typeof(ControlBehavior),
new PropertyMetadata(null));
public static void SetIsEnabledBinding(DependencyObject element, BindingExpression value)
{
if (value != null)
{
element.SetValue(IsEnabledBindingProperty, value);
SetIsEnabledBindingSet(element, true);
}
}
public static BindingExpression GetIsEnabledBinding(DependencyObject element)
{
var obj = element.GetValue(IsEnabledBindingProperty);
return (BindingExpression) obj;
}
public static readonly DependencyProperty IsEnabledBindingSetProperty = DependencyProperty.RegisterAttached(
"IsEnabledBindingSet",
typeof(bool),
typeof(ControlBehavior),
new PropertyMetadata(false));
public static void SetIsEnabledBindingSet(DependencyObject element, bool value)
{
element.SetValue(IsEnabledBindingSetProperty, value);
}
public static bool GetIsEnabledBindingSet(DependencyObject element)
{
return (bool)element.GetValue(IsEnabledBindingSetProperty);
}
public static void ClearIsEnabledBinding(DependencyObject element)
{
SetIsEnabledBinding(element, ((Control)element).GetBindingExpression(UIElement.IsEnabledProperty));
((Control)element).SetBinding(UIElement.IsEnabledProperty, new Binding());
}
public static void RestoreIsEnabledBinding(DependencyObject element)
{
if (!GetIsEnabledBindingSet(element))
{
return;
}
((Control)element).SetBinding(UIElement.IsEnabledProperty, GetIsEnabledBinding(element).ParentBindingBase);
}
}
【问题讨论】:
-
你不能使用简单的触发器吗?
-
我不想在我的视图中添加代码。因为这种行为必须适用于我所有视图的所有控件。
-
IsEnabledBinding 和 IsEnabledBindingSet 属性声明丢失,这反过来又调用了 getproperty 和 setproperty。
-
我不明白你的意思。
-
创建依赖属性时,为propertyName定义一个字符串,检查“IsEnabledBindingProperty”定义。