无法获得由ItemsControl创建的UI元素的属性

问题描述 投票:0回答:1

我在运行时通过使用ItemsControl生成UI元素。 UI会成功生成,但是如果无法获取所生成的UI项的任何属性,例如标签的“ Content”或SelectedItemComboBox。我尝试使用this tutorialthese answers来获取这些属性,但是我总是得到NullReferenceException

XAML中的ItemsControl看起来像这样:

            <ItemsControl Name="ListOfVideos">
                <ItemsControl.Background>
                    <SolidColorBrush Color="Black" Opacity="0"/>
                </ItemsControl.Background>
                <ItemsControl.ItemTemplate>
                    <DataTemplate>
                        <Grid Margin="0,0,0,10">
                            <Grid.ColumnDefinitions>
                                <ColumnDefinition Width="180"/>
                                <ColumnDefinition Width="400"/>
                                <ColumnDefinition Width="200"/>
                            </Grid.ColumnDefinitions>
                            <Image HorizontalAlignment="Left" Height="100" Width="175" x:Name="VideoThumbnailImage" Stretch="Fill" Source="{Binding VideoThumbnailURL}" Grid.Column="0"></Image>
                            <Label x:Name="VideoTitleLabel" Content="{Binding VideoTitleText}" Foreground="White" Grid.Column="1" VerticalAlignment="Top" FontSize="16" FontWeight="Bold"></Label>
                            <Label x:Name="VideoFileSizeLabel" Content="{Binding VideoTotalSizeText}" Foreground="White" FontSize="14" Grid.Column="1" Margin="0,0,0,35" VerticalAlignment="Bottom"></Label>
                            <Label x:Name="VideoProgressLabel" Content="{Binding VideoStatusText}" Foreground="White" FontSize="14" Grid.Column="1" VerticalAlignment="Bottom"></Label>
                            <ComboBox x:Name="VideoComboBox" SelectionChanged="VideoComboBox_SelectionChanged" Grid.Column="2" Width="147.731" Height="20" VerticalAlignment="Bottom" HorizontalAlignment="Center" Margin="0,0,0,50" ItemsSource="{Binding VideoQualitiesList}"></ComboBox>
                            <Label Content="Video Quality" Foreground="White" FontSize="14" VerticalAlignment="Top" Grid.Column="2" HorizontalAlignment="Center"></Label>
                            <Label Content="Audio Quality" Foreground="White" FontSize="14" VerticalAlignment="Bottom" HorizontalAlignment="Center" Margin="0,0,0,27" Grid.Column="2"></Label>
                            <Slider x:Name="VideoAudioSlider" Grid.Column="2" HorizontalAlignment="Center" VerticalAlignment="Bottom" Width="147.731" Maximum="{Binding AudioCount}"></Slider>
                        </Grid>
                    </DataTemplate>
                </ItemsControl.ItemTemplate>
            </ItemsControl>

这是我生成UI元素的方式

public class VideoMetadataDisplay
    {
        public string VideoTitleText { get; set; }
        public int AudioCount { get; set; }
        public string VideoThumbnailURL { get; set; }
        public string VideoStatusText { get; set; }
        public string VideoTotalSizeText { get; set; }
        public List<string> VideoQualitiesList { get; set; }
    }

public partial class PlaylistPage : Page
{
private void GetPlaylistMetadata()
        {

            List<VideoMetadataDisplay> newList = new List<VideoMetadataDisplay>();
            //populate the list
            ListOfVideos.ItemsSource = newList;
        }
}

这就是我试图获取UI元素的属性的方式

public class Utils
    {
        public childItem FindVisualChild<childItem>(DependencyObject obj)
     where childItem : DependencyObject
        {
            for (int i = 0; i < VisualTreeHelper.GetChildrenCount(obj); i++)
            {
                DependencyObject child = VisualTreeHelper.GetChild(obj, i);
                if (child != null && child is childItem)
                {
                    return (childItem)child;
                }
                else
                {
                    childItem childOfChild = FindVisualChild<childItem>(child);
                    if (childOfChild != null)
                        return childOfChild;
                }
            }
            return null;
        }
    }

private void VideoComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            UIElement CurrentItem = (UIElement)ListOfVideos.ItemContainerGenerator.ContainerFromItem(ListOfVideos.Items.CurrentItem);
            Utils utils = new Utils();
            ContentPresenter CurrentContentPresenter = utils.FindVisualChild<ContentPresenter>(CurrentItem);
            DataTemplate CurrentDataTemplate = CurrentContentPresenter.ContentTemplate;
            Label VideoTitle = (Label)CurrentDataTemplate.FindName("VideoTitleLabel", CurrentContentPresenter);
            string VideoTitleText = VideoTitle.Content.ToString();
            MessageBox.Show(VideoTitleText);
        }

[每次我尝试运行此命令时,FindVisualChild总是返回标签之一(VideoTitleLabel),而不是返回当前活动项目的ContentPresenterCurrentDataTemplate为空,因此我无法从中获取任何UI元素。

c# wpf xaml itemscontrol
1个回答
0
投票

FindVisualChild<ContentPresenter>不可能返回Label实例。 FindVisualChild将结果转换为ContentPresenter。由于Labelnot一个ContentPresenter,因此将抛出一个InvalidCastException

短版

仅为了获取其绑定数据而访问DataTemplate或查找控件总是太复杂了。直接访问数据源总是更容易。ItemsControl.SelectedItem将返回所选项目的数据模型。您通常对容器不感兴趣。

private void VideoComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
  var listView = sender as ListView;
  var item = listView.SelectedItem as VideoMetadataDisplay;
  MessageBox.Show(item.VideoTitleText);
}

您的版本(已改进)

FindVisualChild的实现很弱。如果遍历遇到没有子节点的子节点,即参数objnull,它将失败并引发异常。您必须在调用obj之前检查null的参数VisualTreeHelper.GetChildrenCount(obj),以避免引用null

而且您也不需要通过访问模板来搜索元素。您可以直接在视觉树中查找它。我已经修改了您的FindVisualChild方法以按名称搜索元素。为了方便起见,我也将其转换为扩展方法:

扩展方法

public static class Utils
{
  public static bool TryFindVisualChildByName<TChild>(
    this DependencyObject parent,
    string childElementName,
    out TChild childElement)
    where TChild : FrameworkElement
  {
    childElement = null;
    if (parent == null)
    {
      return false;
    }

    for (int i = 0; i < VisualTreeHelper.GetChildrenCount(parent); i++)
    {
      DependencyObject child = VisualTreeHelper.GetChild(parent, i);
      if (child is TChild resultElement && resultElement.Name.Equals(childElementName, StringComparison.Ordinal))
      {
        childElement = resultElement;
        return true;
      }

      if (child.TryFindVisualChild(childElementName, out childElement))
      {
        return true;
      }
    }

    return false;
  }
}

示例

private void VideoComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
  var listView = sender as ListView;
  object item = listView.SelectedItem;
  var itemContainer = listView.ItemContainerGenerator.ContainerFromItem(item) as ListViewItem;

  if (itemContainer.TryFindVisualChild("VideoTitleLabel", out Label label))
  {
    var videoTitleText = label.Content as string;
    MessageBox.Show(videoTitleText);
  }
}
© www.soinside.com 2019 - 2024. All rights reserved.