【问题标题】:How to bind the width to the widest successor (recurrently any child of any child)?如何将宽度绑定到最宽的继任者(通常是任何孩子的任何孩子)?
【发布时间】:2015-08-11 13:44:56
【问题描述】:

我使用下面的语法。

<Canvas Width="{Binding ActualWidth, ElementName=Beep}">
  ...
</Canvas>

目前,Beep 是画布下最宽的控件,但不能保证保持这种状态。我需要将宽度绑定到最宽的画布的任何后继者(即任何孩子的孩子,反复地说)。

我该怎么做?

【问题讨论】:

    标签: wpf xaml canvas data-binding


    【解决方案1】:

    我没有测试它,但你可以尝试这样的事情。 在xml中:

    <local:Converter x:Key="converter"/>
    <Canvas Width="{Binding Path=Children, RelativeSource={RelativeSource Self}}" Converter="{StaticResource converter}"">
    
    </Canvas>
    

    转换器可能和这个类似:

    public class Converter:IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            UIElementCollection children=value as UIElementCollection;
            double ret=0.0;
            recursiveSearch(children, ref ret);
            return ret;
        }
        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            throw new NotImplementedException();
        }
        private void recursiveSearch(UIElementCollection children, ref double width)
        {
            if(children == null || children.Count==0) return;
            foreach(UIElement element in children)
            {
                FrameworkElement el=element as FrameworkElement;
                if(el == null) continue;
                if(el.ActualWidth>width) width=el.ActualWidth;
                Panel p=el as Panel;
                if(p!=null) recursiveSearch(p.Children, ref width);
            }
        }
    }
    

    【讨论】:

      【解决方案2】:

      尝试绑定到您感兴趣的所有控件的集合。然后编写一个转换器并从集合中选择最广泛的控件。

      如果您没有控件集合,当然也可以使用多重绑定。

      【讨论】:

      • 听起来如果设置一个应该超过所有其他的固定宽度更容易......还是我高估了需要多少代码?愿意提供一些代码示例还是一项更大的工作? (后一种情况,我就按Q&D的方式做,呵呵。)
      猜你喜欢
      • 2017-07-02
      • 1970-01-01
      • 2019-09-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-05-29
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多