Databinding to CLR property in code
Binding to a Dependency Property is easy in code-behind. You just create a new System.Windows.Data.Binding
object, and then call the target dependency object's SetBinding
method.
But how do you do this when the property which we're binding is a CLR property and you can't provide a DependencyProperty
argument to SetBinding
?
EDIT: The object implements INotifyPropertyChanged
, if that's relevant.
Binding targets MUST be dependency properties! That's the only requirement for databinding to work!
Read more here:
If I understand your question correctly you have a FrameworkElement
that exposes a plain old ordinary property that isn't backed up as a Dependency property. However you would like to set it as the target of a binding.
First off getting TwoWay binding to work would be unlikely and in most cases impossible. However if you only want one way binding then you could create an attached property as a surrogate for the actual property.
Lets imagine I have a StatusDisplay
framework element that has a string Message
property that for some really dumb reason doesn't support Message
as a dependency property.
public static StatusDisplaySurrogates
{
public static string GetMessage(StatusDisplay element)
{
if (element == null)
{
throw new ArgumentNullException("element");
}
return element.GetValue(MessageProperty) as string;
}
public static void SetMessage(StatusDisplay element, string value)
{
if (element == null)
{
throw new ArgumentNullException("element");
}
element.SetValue(MessageProperty, value);
}
public static readonly DependencyProperty MessageProperty =
DependencyProperty.RegisterAttached(
"Message",
typeof(string),
typeof(StatusDisplay),
new PropertyMetadata(null, OnMessagePropertyChanged));
private static void OnMessagePropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
StatusDisplay source = d as StatusDisplay;
source.Message = e.NewValue as String;
}
}
Of course if the StatusDisplay
control has its Message
property modified directly for any reason the state of this surrogate will no longer match. Still that may not matter for your purposes.
Wait. Are you trying to bind 2 CLR properties?? Let me say such thing is impossible to achieve in normal way. eg. no kind of hardcore hack that can make your whole application unstable. One side of binding MUST be DependencyProperty. Period.
链接地址: http://www.djcxy.com/p/48402.html上一篇: 大规模并行螺纹读取的Azure表存储性能
下一篇: 数据绑定到代码中的CLR属性