绑定未更新 - 添加检测面板的儿童
我目前正在实施一种继承自Panel
的Layout Conainer,并且能够检测Panel.Children
中的更改并检测新元素/已删除元素。绑定未更新 - 添加检测面板的儿童
目前,我有一个依赖属性绑定到Panel.Children.Count
值,这非常笨重,但我不知道创建此类侦听器的更好方法。
public abstract class MyLayoutContainer : Panel
{
private Binding countBinding;
// ctor...
private void InitializeBinding()
{
countBinding = new Binding("Count");
countBinding.Source = this.Children;
// Using the comment below instead of "Count"
// in the Binding constructor throws an error
//countBinding.Path = new PropertyPath(UIElementCollection.CountProperty);
countBinding.Mode = BindingMode.OneWay;
BindingOperations.SetBinding(this, MyLayoutContainer.BoundChildCountProperty, countBinding);
}
// ...
private static readonly DependencyProperty BoundChildCountProperty
= DependencyProperty.Register
(
"BoundChildCount",
typeof(int),
typeof(MyLayoutContainer),
new PropertyMetadata(0, ChildCountChange)
);
private static int GetBoundChildCount(MyLayoutContainer depObj)
{
return (int)depObj.GetValue(BoundChildCountProperty);
}
private static void SetBoundVisibility(MyLayoutContainer depObj, int value)
{
depObj.SetValue(BoundChildCountProperty, value);
}
private static void ChildCountChange(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
MyLayoutContainer mlc = d as MyLayoutContainer;
// For testing, this function is currently empty
// however normally it checks children against a
// shadow list, or will remove them as they're
// added.
mlc.ChildrenChanged(e.OldValue, e.NewValue);
}
}
问题是它只更新一次。这几乎就好像我已经设置了BindingMode.OneTime
,情况并非如此。当我检查BoundChildCountProperty
与this.Children.Count
时,我得到1和4.我不知道发生了什么,因为我已经使用了完全相同的方法来绑定另一个对象的可见性来创建“侦听器”。另外,我在XAML设计器中获得了更好的功能(如果有很多令人讨厌的MessageBoxes,那么当我将它们放在那里的时候......)在加载所有对象时会更好。
请,如果有人知道这样做的更好方法,或者可以看到我做错了什么,我会非常,非常感谢!
编辑 - 更多信息: 我的最终目标是创建一个灵活的类,它可以扩展任何当前面板类(如电网和StackPanels)的和,因为他们密封覆盖功能,我希望能找到一个检测添加的孩子的解决方法等。
您应该重写方法ArrangeOverride
和MeasureOverride
,这些是您进行自定义布局的位置。无论何时只要Children
成员资格发生变化,他们都会被召唤出于各种原因。
@AWJ感谢您的回答,但是......部分问题是我想创建一个扩展的Grid类,并且由于C#中相当令人沮丧的'sealed'修饰符,我无法在子类中重写这些函数-类。 目前,我正在动态创建基本面板类型(StackPanel,Grid,Canvas等)的成员,并试图将添加到此类的子成员移到成员类中。很烦躁,但我没有看到它的方式。 – Melodatron 2011-05-20 11:59:20
@Melodatron:在这种情况下,为什么要使用Panel的衍生产品?从一个简单的自定义控件开始,它具有一个'Panel'作为必需的'TemplatePart'。使用您可以控制的集合类型实现您自己的“Children”属性,并以您认为合适的方式将成员转发到内部“Panel”。 – AnthonyWJones 2011-05-20 12:23:44
@AWJ我会放弃一切,回到你身边。谢谢你的帮助。 – Melodatron 2011-05-20 12:27:30
虽然此问题尚未直接解决,但下面AnthonyWJones提出的解决方案对于处于类似情况的人来说是一种令人满意的解决方法。 – Melodatron 2011-05-23 15:27:32