WPF ObservableCollection <t>从添加的元素中获取ui引用

时间:2016-04-19 07:05:29

标签: c# wpf

我遇到了一个问题,我希望返回一个UI引用(在将项添加到ObservableCollection之后)。因此,当一个项目被添加到集合中时,我想获得&#34; Border&#34;参考

一直试图谷歌寻求解决方案,但我找不到。

XAML,我想要的是返回Datatemplate中的Border(这可能吗?)

 <ItemsControl ItemsSource="{Binding Elements}">
        <ItemsControl.ItemsPanel>
            <ItemsPanelTemplate>
                <StackPanel Margin="37,0,0,0" Orientation="Horizontal" HorizontalAlignment="Left" Width="590" Height="29" />
            </ItemsPanelTemplate>
        </ItemsControl.ItemsPanel>
        <ItemsControl.ItemContainerStyle>
            <Style TargetType="{x:Type ContentPresenter}" />
        </ItemsControl.ItemContainerStyle>
        <ItemsControl.ItemTemplate>
            <DataTemplate>
                <Border Width="{Binding Style.Background.Width}" Margin="{Binding Style.Background.Position, Converter={StaticResource LeftMarginConverter}}" BorderThickness="{Binding Style.Background.BorderSize}" BorderBrush="{Binding Style.Background.BorderColor, Converter= {StaticResource MediaBrushConverter}}" Height="27" HorizontalAlignment="Center" VerticalAlignment="Center">
                    <Border.Background>
                        <LinearGradientBrush GradientStops="{Binding Style.Background.Background, Converter={StaticResource GradientConverter}}" Opacity="{Binding Style.Background.Opacity}"/>
                    </Border.Background>

                    <StackPanel Orientation="Horizontal" VerticalAlignment="Center" HorizontalAlignment="Center">
                        <TextBlock Text="{Binding Value}" FontFamily="{Binding Style.Value.Font, Converter= {StaticResource FontConverter}}" Foreground="{Binding Style.Value.FontColor, Converter= {StaticResource MediaBrushConverter}}" FontSize="{Binding Style.Value.FontSize}" TextAlignment="Center"  Opacity="1" HorizontalAlignment="Center" VerticalAlignment="Center" />
                        <TextBlock Text="{Binding TextExtension}" FontFamily="{Binding Style.Value.Font, Converter= {StaticResource FontConverter}}" Foreground="#eaeaea" FontSize="{Binding Style.Value.FontSize}" TextAlignment="Center"  Opacity="1" HorizontalAlignment="Center" VerticalAlignment="Center" />
                    </StackPanel>
                </Border>
            </DataTemplate>
        </ItemsControl.ItemTemplate>
    </ItemsControl>


        foreach(var x in Elements) //  Elemets = ObservableCollection 
        {
            var i =FControls.ItemContainerGenerator.ContainerFromItem(x) as Border;

            MessageBox.Show(i.ToString()); /// Returns null
        }

1 个答案:

答案 0 :(得分:0)

不幸的是,ObservableCollection并未提供您想要的功能。您可以使用ItemsControl.ItemContainerGenerator.ContainerFromItem()获取包裹ContentControl的{​​{1}}。