问题
Short question
Is there a quick way of knowing what a particular attached property is bound to, at runtime?
Detail
I'm debugging a UserControl (that inherits ItemsControl
) which binds Canvas.Left
and Canvas.Top
of its items to two properties of the ViewModel objects, through a style. At runtime, I place a breakpoint at a certain location and want to inspect the binding of Canvas.Left
attached property.
Note that I do not want to see the current value of the attached property for an item. I can easily do that by inspecting the value of Canvas.GetLeft(myItem)
in the QuickWatch or Immediate windows. I want to check the actual binding here, i.e. the VM property name to which this attached property is bound for myItem
.
I have tried Snoop already, which unfortunately doesn't show bindings of attached properties (if I didn't miss something obvious).
回答1:
Is there a quick way of knowing what a particular attached property is bound to, at runtime
Yes, just override attached property somewhere (in your window?):
<Window x:Class="WpfApplication1.MainWindow" ... >
<Grid Canvas.Top="123"/>
</Window>
and code
public MainWindow()
{
InitializeComponent();
Canvas.TopProperty.OverrideMetadata(typeof(MainWindow), new FrameworkPropertyMetadata((d, e) =>
{
// you will get here for each Canvas.Top set in MainWindow
MessageBox.Show(d.ToString());
}));
}
回答2:
You can get the attached property binding programmatically the same way as you get normal dependency property binding. I.e. from code behind to get the Canvas.LeftProperty
attached property binding of the control with the name myItemsControl
:
BindingExpression bindingExpression = myItemsControl.GetBindingExpression(Canvas.LeftProperty);
Binding parentBinding = bindingExpression.ParentBinding;
来源:https://stackoverflow.com/questions/31857194/attached-property-check-binding