简体   繁体   中英

C# WPF better way to iterate on children and change property

I have to iterate through all children of a stackPanel. Being new to WPF I do that

foreach (var item in spTab3.Children)
  {
    if (item.GetType() == typeof(ListBox))
      ((ListBox)item).Visibility = Visibility.Collapsed;
     if (item.GetType() == typeof(Grid))
      ((Grid)item).Visibility = Visibility.Collapsed;
    ....
  }

that is I have to cast all types of elements to get to set the visibility. I bet there is a smarter way to do all the togheter. Thanks

---EDIT--- So in short I have a stackpanel spTab3 with children. When I do what suggested by Bijington:

spTab3.Visibility = Visibility.Collapsed;<----------set all children to collapsed
spTab3.Children[iVisibleTab-1].Visibility = Visibility.Visible;<----set only one to visible

the second line has no effect. While when I do as stated by Spawn that works:

foreach (var item in spTab3.Children)
    ((UIElement)item).Visibility = Visibility.Collapsed;

 spTab3.Children[iVisibleTab-1].Visibility = Visibility.Visible;

can anyone explain me why?!?

Every child in Panel is UIElement. So its type derived from DependencyObject which has SetValue method. Use it.

foreach (UIElement item in spTab3.Children)
{
    item.SetValue(UIElement.VisibilityProperty, Visibility.Collapsed (or Visible));
}

Keep in mind that it's not a WPF style solution. You better need to declare dependency property and to bind item's visibility to this property.

In case that panel and code are inside a Window

public static readonly DependencyProperty IsItemVisibleProperty = DependencyProperty.Register("IsItemVisible", typeof(Visibility), typeof(MainWindow), new FrameworkPropertyMetadata(Visibility.Visible));

public Visibility IsItemVisible
{
    get
    {
        return (Visibility)GetValue(IsItemVisibleProperty);
    }
    set
    {
        SetValue(IsItemVisibleProperty, value);
    }
}

XAML:

<Window x:Class="WpfApplication1.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="350" Width="525">
    <StackPanel>
        <Button Visibility="{Binding IsItemVisible,RelativeSource={RelativeSource AncestorType=Window}}">Collapsed 1</Button>
        <Button Visibility="{Binding IsItemVisible,RelativeSource={RelativeSource AncestorType=Window}}">Collapsed 2</Button>
        <Button>Visible</Button>
    </StackPanel>
</Window>

StackPanel中显示/隐藏Children的更有效方法是在StackPanel本身上简单地设置Visibility属性。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM