【问题标题】:MyContainer derived from FrameworkElement with binding supportMyContainer 从 FrameworkElement 派生并支持绑定
【发布时间】:2009-04-04 22:14:54
【问题描述】:

为了了解绑定的工作原理,我实现了从 FrameworkElement 派生的 MyContainer。此容器允许设置子项并将它们添加到逻辑树中。但是 ElementName 的绑定不起作用。我可以用 MyContainer 做什么来使其工作,将父级保留为 FrameworkElement?

C#:

public class MyContainer : FrameworkElement
{
    public MyContainer()
    {
        Children = new List<FrameworkElement>();
    }

    public List<FrameworkElement> Children { get; set; }
    protected override IEnumerator LogicalChildren
    {
        get { return Children.GetEnumerator(); }
    }
}

XAML:

<Window x:Class="WpfLogicalTree.Window1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="clr-namespace:WpfLogicalTree"
    Title="Window1" Height="300" Width="300">
    <StackPanel>

        <local:MyContainer>
            <local:MyContainer.Children>
                <TextBlock Text="Foo" x:Name="_source" />
                <TextBlock Text="{Binding Path=Text, ElementName=_source}" x:Name="_target"/>
            </local:MyContainer.Children>   
        </local:MyContainer>

        <Button Click="Button_Click">Test</Button>

    </StackPanel>
</Window>

Window1.cs

private void Button_Click(object sender, RoutedEventArgs e)
{
    MessageBox.Show(_target.Text);
}

【问题讨论】:

    标签: wpf binding


    【解决方案1】:

    我不得不调用 AddLogicalChild,而不是使用 LogicalChildren。所以这行得通:

    public class MyContainer : FrameworkElement
    {
        public MyContainer()
        {
            Children = new List<FrameworkElement>();
            this.Loaded += new RoutedEventHandler(OnLoaded);
        }
    
        void  OnLoaded(object sender, RoutedEventArgs e)
        {
            foreach (FrameworkElement fe in Children)
                this.AddLogicalChild(fe);
        }        
    
        public List<FrameworkElement> Children { get; set; }
    }
    

    AddLogicalChild 设置元素的逻辑父级,这是查找注册“_source”名称的 NameScope 所必需的。在我们的例子中,名称范围是 Window1。

    注意。 AddLogicalChild 不会导致 LogicalChildren 自动返回我们的孩子,它只会设置 Parent。所以 LogicalTreeHelper.GetChildren 将是空集合。但我们这里不需要它。

    【讨论】:

      猜你喜欢
      • 2011-01-05
      • 2011-04-04
      • 1970-01-01
      • 1970-01-01
      • 2019-10-25
      • 1970-01-01
      • 2014-07-02
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多