您可以使用BindingDecoratorBase來使用自定義綁定並使用屬性。
以下代碼只是我在使用custom validation的項目中修改我的代碼。它可能應該折射。
public interface IEditatble
{
void SetValue(Control sender, DependencyProperty property);
}
[AttributeUsage(AttributeTargets.Property)]
public class EditableAttribute : Attribute, IEditatble
{
public EditableAttribute(bool isEditable)
{
this.ReadOnly = !isEditable;
}
public virtual bool ReadOnly { get; set; }
public void SetValue(System.Windows.Controls.Control sender, System.Windows.DependencyProperty property)
{
sender.SetValue(property, this.ReadOnly);
}
}
您可以創建自定義綁定:
public class ReadonlyBinding : BindingDecoratorBase
{
private DependencyProperty _targetProperty = null;
public ReadonlyBinding()
: base()
{
Binding.UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged;
}
public override object ProvideValue(IServiceProvider provider)
{
// Get the binding expression
object bindingExpression = base.ProvideValue(provider);
// Bound items
DependencyObject targetObject;
// Try to get the bound items
if (TryGetTargetItems(provider, out targetObject, out _targetProperty))
{
if (targetObject is FrameworkElement)
{
// Get the element and implement datacontext changes
FrameworkElement element = targetObject as FrameworkElement;
element.DataContextChanged += new DependencyPropertyChangedEventHandler(element_DataContextChanged);
}
}
// Go on with the flow
return bindingExpression;
}
void element_DataContextChanged(object sender, DependencyPropertyChangedEventArgs e)
{
object datacontext = e.NewValue;
if (datacontext != null && _targetProperty != null)
{
PropertyInfo property = datacontext.GetType().GetProperty(Binding.Path.Path);
if (property != null)
{
var attribute = property.GetCustomAttributes(true).Where(o => o is IEditatble).FirstOrDefault();
if (attribute != null)
{
Control cntrl = sender as Control;
((IEditatble)attribute).SetValue(cntrl, _targetProperty);
}
}
}
}
}
而且你可以用它喜歡:
[Editable(true)]
public string Name { get; set; }
的XAML:
<TextBox IsReadOnly="{local:ReadonlyBinding Path=Name}" />