zerodoc zerodoc - 2 months ago 26
C# Question

WPF code to turn visibility off:on of multiple stackpanels

I have multiple stackpanels that are collapsed at first and as a button is clicked the stackpanel relating to the button click becomes visible. As off right now this is what I have that works.

private void Button1_Click(object sender, RoutedEventArgs e)
dgrid.ItemsSource = FillDataGrid("ShipWorksConnection", "GetPicklistItems", "PickList");

SP1.Visibility = Visibility.Visible;
SP2.Visibility = Visibility.Collapsed;
SP3.Visibility = Visibility.Collapsed;
SP4.Visibility = Visibility.Collapsed;

private void Button2_Click(object sender, RoutedEventArgs e)
dgrid.ItemsSource = FillDataGrid("SupplyConnection", "GetAllSupplies", "Supplies");

SP1.Visibility = Visibility.Collapsed;
SP2.Visibility = Visibility.Visible;
SP3.Visibility = Visibility.Collapsed;
SP4.Visibility = Visibility.Collapsed;


and so on for multiple button click events. Is this the way to handle this and since I'll be adding more button click events is there something else I could do to make the code more reusable.


If there is some combined logic in the hiding / showing of elements, you can use a binding to toggle the visibility.

For this sample, you have to create a viewmodel and create a property TheConditionProperty in it. Then bind the view model to the control. In your scenario, you can even bind to an array of items, which will make it easier than adding properties over and over again.

        <Style TargetType="StackPanel">
                <DataTrigger Binding="{Binding TheConditionProperty}" Value="False">
                    <Setter Property="Visibility" Value="Collapsed" />