c# не может установить видимость родительского элемента управления на «Visible» и дочерний элемент управления на «Collapsed» - PullRequest
0 голосов
/ 07 мая 2020

РЕДАКТИРОВАТЬ

Я реструктурирую вопрос, чтобы сделать его более ясным.

Приложение, над которым я работаю, имеет экран регистрации (называется MainWindow) и основное приложение (называемое HomeWindow).

Как только пользователь вводит свои учетные данные, запускается событие щелчка (я сократил код для простоты)

private void BtnHello_Click(object sender, RoutedEventArgs e)
{
   HomeWindow homeWindow = new HomeWindow();
   MainWindow mainWindow = new MainWindow();
   HRLevel1UserControl hRLevel1UserControl = new HRLevel1UserControl();
   StudentsLevel1UserControl studentsLevel1UserControl = new StudentsLevel1UserControl();

    homeWindow.ItemHR.Visibility = Visibility.Collapsed;
    homeWindow.ItemStudents.Visibility = Visibility.Collapsed;
    homeWindow.ItemClass.Visibility = Visibility.Collapsed;
    homeWindow.ItemFinances.Visibility = Visibility.Collapsed;
    homeWindow.ItemSchool.Visibility = Visibility.Collapsed;
    homeWindow.ItemReports.Visibility = Visibility.Collapsed;

    foreach (UserCategory userCategory in new CheckConnection().CheckPrivilege(LoggedInData.LoggedInUserId, LoggedInData.LoggedInstitutionId))
    {
      if (userCategory.Role == TeacherRole)
      {                                                
       homeWindow.ItemStudents.Visibility = Visibility.Visible;                                                
       studentsLevel1UserControl.StudentManageBtn.Visibility = Visibility.Collapsed;                                                
       studentsLevel1UserControl.StudentReportBtn.Visibility = Visibility.Collapsed;                                                
       homeWindow.MenuBarSettings.Visibility = Visibility.Collapsed;
       }
       else
       {
          MessageBox.Show("-", MessageBoxButton.OK, MessageBoxImage.Stop);
          return;
       }
    }
   this.Close();
   homeWindow.Show();
}

The homeWindow - это главное окно приложения, которое создается на основе следующего XAML:

<Grid>
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto"/>
            <RowDefinition Height="*"/>
        </Grid.RowDefinitions>
        <Grid Grid.Row="2">
            <Frame BorderBrush="DarkGray" BorderThickness="2"/>
            <Grid Name="MainGrid" Background="White" Margin="140 5 5 5" HorizontalAlignment="Stretch"/>
            <Grid Margin="4 4 0 5" Width="132" HorizontalAlignment="Left">
                <Grid.Background>
                    <LinearGradientBrush EndPoint="0.5,2.5" StartPoint="1,0" MappingMode="RelativeToBoundingBox" SpreadMethod="Pad" Opacity="0.3">
                        <GradientStop Color="Black" Offset="1"/>
                        <GradientStop Color="White" Offset="0"/>
                    </LinearGradientBrush>
                </Grid.Background>
                <Grid.RowDefinitions>
                    <RowDefinition Height="*"/>
                    <RowDefinition Height="8*"/>
                </Grid.RowDefinitions>
                <Image Source="{DynamicResource Logo}" ToolTip="Sire Systems" HorizontalAlignment="Left"/>
                <ListView x:Name="ListViewMain" Grid.Row="1" Background="Transparent" SelectionMode="Single" ScrollViewer.HorizontalScrollBarVisibility="Disabled" SelectionChanged="ListViewMain_SelectionChanged">
                    <ListView.BorderBrush>
                        <LinearGradientBrush EndPoint="0.5,1" StartPoint="0.5,0">
                            <GradientStop Color="Black"/>
                            <GradientStop Color="White" Offset="1"/>
                        </LinearGradientBrush>
                    </ListView.BorderBrush>
                    <ListViewItem BorderThickness="0" Background="Transparent" Foreground="Transparent" Width="128" x:Name="ItemAccueil" HorizontalAlignment="Left" ToolTip="Accueil">
                        <StackPanel Orientation="Horizontal">
                            <Image Margin="5" Source="{DynamicResource Dashboard}"/>
                            <TextBlock Text="Accueil" VerticalAlignment="Center" FontSize="14" FontWeight="DemiBold" Foreground="#FF606060"/>
                        </StackPanel>
                    </ListViewItem>
                    <ListViewItem BorderThickness="0" Background="Transparent" Foreground="Transparent" Width="128" x:Name="ItemHR" HorizontalAlignment="Left" ToolTip="Ressources Humaines">
                        <StackPanel Orientation="Horizontal">
                            <Image Margin="5" Source="{DynamicResource HR}"/>
                            <TextBlock Text="RH" VerticalAlignment="Center" FontSize="14" FontWeight="DemiBold" Foreground="#FF606060"/>
                        </StackPanel>
                    </ListViewItem>
                    <ListViewItem BorderThickness="0" Background="Transparent" Foreground="Transparent" Width="128" x:Name="ItemStudents" HorizontalAlignment="Left" ToolTip="Gestion Etudiants">
                        <StackPanel Orientation="Horizontal">
                            <Image Margin="5" Source="{DynamicResource Students}"/>
                            <TextBlock Text="Etudiants" VerticalAlignment="Center" FontSize="14" FontWeight="DemiBold" Foreground="#FF606060"/>
                        </StackPanel>
                    </ListViewItem>
                    <ListViewItem BorderThickness="0" Background="Transparent" Foreground="Transparent" Width="128" x:Name="ItemClass" HorizontalAlignment="Left" ToolTip="Gestion Classes">
                        <StackPanel Orientation="Horizontal">
                            <Image Margin="5" Source="{DynamicResource Classes}"/>
                            <TextBlock Text="Classes" VerticalAlignment="Center" FontSize="14" FontWeight="DemiBold" Foreground="#FF606060"/>
                        </StackPanel>
                    </ListViewItem>
                    <ListViewItem BorderThickness="0" Background="Transparent" Foreground="Transparent" Width="128" x:Name="ItemFinances" HorizontalAlignment="Left" ToolTip="Gestion Finances">
                        <StackPanel Orientation="Horizontal">
                            <Image Margin="5" Source="{DynamicResource Finances}"/>
                            <TextBlock Text="Finances" VerticalAlignment="Center" FontSize="14" FontWeight="DemiBold" Foreground="#FF606060"/>
                        </StackPanel>
                    </ListViewItem>
                    <ListViewItem BorderThickness="0" Background="Transparent" Foreground="Transparent" Width="128" x:Name="ItemSchool" HorizontalAlignment="Left" ToolTip="Gestion au Quotidien">
                        <StackPanel Orientation="Horizontal">
                            <Image Margin="5" Source="{DynamicResource School}"/>
                            <TextBlock Text="Ecole" VerticalAlignment="Center" FontSize="14" FontWeight="DemiBold" Foreground="#FF606060"/>
                        </StackPanel>
                    </ListViewItem>
                    <ListViewItem BorderThickness="0" Background="Transparent" Foreground="Transparent" Width="128" x:Name="ItemReports" HorizontalAlignment="Left" ToolTip="Rapports Globaux">
                        <StackPanel Orientation="Horizontal">
                            <Image Margin="5" Source="{DynamicResource Reports}"/>
                            <TextBlock Text="Rapports" VerticalAlignment="Center" FontSize="14" FontWeight="DemiBold" Foreground="#FF606060"/>
                        </StackPanel>
                    </ListViewItem>
                </ListView>
            </Grid>                        
        </Grid>        
    </Grid>

Каждый ListViewItem загружает пользовательский элемент управления в MainGrid на основе следующего кода:

private void ListViewMain_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            UserControl usc = null;
            //MainGrid.Children.Clear();

            try
            {
                switch (((ListViewItem)((ListView)sender).SelectedItem).Name)
                {
                    case "ItemAccueil":
                        usc = new HomeUserControl();
                        MainGrid.Children.Add(usc);
                        break;
                    case "ItemHR":
                        usc = new UserControls.Home.HRLevel1UserControl() { VerticalAlignment = VerticalAlignment.Stretch };
                        MainGrid.Children.Add(usc);
                        break;
                    case "ItemStudents":
                        usc = new UserControls.Students.StudentsLevel1UserControl() { VerticalAlignment = VerticalAlignment.Stretch };
                        MainGrid.Children.Add(usc);
                        break;
                    case "ItemClass":
                        usc = new UserControls.Classes.ClassLevel1UserControl() { VerticalAlignment = VerticalAlignment.Stretch };
                        MainGrid.Children.Add(usc);
                        break;
                    case "ItemFinances":
                        usc = new UserControls.Finances.FinancesLevel1UserControl() { VerticalAlignment = VerticalAlignment.Stretch };
                        MainGrid.Children.Add(usc);
                        break;
                    case "ItemSchool":
                        usc = new UserControls.School.SchoolLevel1UserControl() { VerticalAlignment = VerticalAlignment.Stretch };
                        MainGrid.Children.Add(usc);
                        break;
                    case "ItemReports":
                        usc = new UserControls.Reports.ReportsLevel1UserControl() { VerticalAlignment = VerticalAlignment.Stretch };
                        MainGrid.Children.Add(usc);
                        break;
                    default:
                        usc = new HomeUserControl();
                        MainGrid.Children.Add(usc);
                        break;
                }
            }
            catch (Exception ex)
            {

                MessageBox.Show(ex.Message);
                return;
            }
        }

Один из загружаемых пользовательских элементов управления - это студенты us c, называемые StudentsLevel1UserControl (см. Часть кода: case "ItemStudents"). И вот XAML для этого пользовательского элемента управления:

<Grid Style="{StaticResource UpperGridStyle}">
        <StackPanel Style="{StaticResource UscMenuBarStyle}">
            <StackPanel.Resources>
                <Style x:Key="MenuButtonStyle" TargetType="RadioButton" BasedOn="{StaticResource {x:Type ToggleButton}}">
                    <Setter Property="Background" Value="{x:Null}"/>
                    <Setter Property="BorderBrush" Value="{x:Null}"/>
                    <Setter Property="BorderThickness" Value="0"/>
                    <Setter Property="TextBlock.FontWeight" Value="DemiBold"/>
                    <Style.Triggers>
                        <DataTrigger Binding="{Binding Path=IsChecked, RelativeSource={RelativeSource Self}}" Value="True">
                            <Setter Property="Background" Value="LightBlue"/>
                            <Setter Property="BorderBrush" Value="#FF005C8B"/>
                            <Setter Property="BorderThickness" Value="1"/>
                            <Setter Property="TextBlock.FontWeight" Value="Bold"/>
                            <Setter Property="TextBlock.Foreground" Value="#FF3284CB"/>
                            <Setter Property="TextBlock.FontSize" Value="12.5"/>
                        </DataTrigger>
                    </Style.Triggers>
                </Style>
            </StackPanel.Resources>
            <RadioButton Uid="0" x:Name="StudentManageBtn" Width="120" Content="Gestion Etudiants" Height="Auto" Style="{StaticResource MenuButtonStyle}" Click="Button_Click"/>
            <RadioButton Uid="1" x:Name="StudentRatingsBtn" Width="130" Content="Evaluations" Height="Auto" Style="{StaticResource MenuButtonStyle}" Click="Button_Click"/>
            <RadioButton Uid="2" x:Name="StudentPassingBtn" Width="120" Content="Passage de Classe" Height="Auto" Style="{StaticResource MenuButtonStyle}" Click="Button_Click"/>
            <RadioButton Uid="3" x:Name="StudentReportBtn" Width="120" Content="Rapports Etudiants" Height="Auto" Style="{StaticResource MenuButtonStyle}" Click="Button_Click"/>            
        </StackPanel>
        <Grid x:Name="StudentsMain" Margin="5 55 5 5" VerticalAlignment="Stretch"/>
    </Grid>

Как видите, этот пользовательский элемент управления содержит четыре RadioButtons, и то, что я пытаюсь достичь, - это Visibility из StudentManageBtn и * 1031 От * до COllapsed в зависимости от того, является ли входящий в систему пользователь учителем или нет. Пока что метод, который я использовал (в кнопке BtnHello_Click), не работает.

Для полноты, вот код программной части для пользовательского элемента управления

public partial class StudentsLevel1UserControl : UserControl
    {
        public StudentsLevel1UserControl()
        {
            InitializeComponent();
            UserControl usctrl = new StudentsManageStudentsUsc();
            StudentsMain.Children.Add(usctrl);
            StudentManageBtn.IsChecked = true;
        }
        private void Button_Click(object sender, RoutedEventArgs e)
        {
            int index = int.Parse(((RadioButton)e.Source).Uid);
            StudentsMain.Children.Clear();
            UserControl usctrl = null;
            switch (index)
            {
                case 0:
                    usctrl = new StudentsManageStudentsUsc() { VerticalAlignment = VerticalAlignment.Stretch };
                    StudentsMain.Children.Add(usctrl);
                    break;
                case 1:
                    usctrl = new StudentsEvaluateStudentsUsc() { VerticalAlignment = VerticalAlignment.Stretch };
                    StudentsMain.Children.Add(usctrl);
                    break;
                case 2:
                    usctrl = new StudentsClassPassingUsc() { VerticalAlignment = VerticalAlignment.Stretch };
                    StudentsMain.Children.Add(usctrl);
                    break;
                case 3:
                    usctrl = new StudentsReportsUsc() { VerticalAlignment = VerticalAlignment.Stretch };
                    StudentsMain.Children.Add(usctrl);
                    break;
            }
        }
    }

1 Ответ

0 голосов
/ 09 мая 2020

Я рекомендую использовать DataTrigger внутри соответствующего Style.

Чтобы он работал, убедитесь, что UserCategory является свойством publi c для MainWindow.

В следующем примере определяются два стиля для RadioButton: существующий стиль MenuButtonStyle, который применяется к каждому RadioButton, не имеющему ограничений Visibility.
И на основе существующего MenuButtonStyle нового MenuButtonTeacherVisibiltyStyle. При применении к соответствующим кнопкам они сворачиваются, если роль пользователя - TeacherRole:

MainWindow.xaml.cs

private void BtnHello_Click(object sender, RoutedEventArgs e)
{
  HomeWindow homeWindow = new HomeWindow() {Role = this.UserCategory.Role};

  this.Close();
  homeWindow.Show();
}

StudentsLevel1UserControl.xaml

<UserControl>
  <UserControl.Resources>
    <Style x:Key="MenuButtonStyle" TargetType="RadioButton" BasedOn="{StaticResource {x:Type ToggleButton}}">
      <Setter Property="Background" Value="{x:Null}"/>
      <Setter Property="BorderBrush" Value="{x:Null}"/>
      <Setter Property="BorderThickness" Value="0"/>
      <Setter Property="TextBlock.FontWeight" Value="DemiBold"/>
      <Style.Triggers>
        <DataTrigger Binding="{Binding Path=IsChecked, RelativeSource={RelativeSource Self}}" Value="True">
          <Setter Property="Background" Value="LightBlue"/>
          <Setter Property="BorderBrush" Value="#FF005C8B"/>
          <Setter Property="BorderThickness" Value="1"/>
          <Setter Property="TextBlock.FontWeight" Value="Bold"/>
          <Setter Property="TextBlock.Foreground" Value="#FF3284CB"/>
          <Setter Property="TextBlock.FontSize" Value="12.5"/>
        </DataTrigger>
      </Style.Triggers>
    </Style>

    <Style x:Key="MenuButtonTeacherVisibiltyStyle" 
           TargetType="RadioButton" 
           BasedOn="{StaticResource MenuButtonStyle}">
      <Setter Property="Visibility" Value="Visible"/>
      <Style.Triggers>
        <DataTrigger Binding="{Binding RelativeSource={RelativeSource AncestorType=HomeWindow}, Path=Role}" Value="TeacherRole">
          <Setter Property="Visibility" Value="Collapsed"/>
        </DataTrigger>
      </Style.Triggers>
    </Style>
  </UserControl.Resources>

  <StackPanel>
    <RadioButton x:Name="StudentManageBtn" Style="{StaticResource MenuButtonTeacherVisibiltyStyle}" Click="Button_Click"/>
    <RadioButton x:Name="StudentRatingsBtn" tyle="{StaticResource MenuButtonStyle}" Click="Button_Click"/>
    <RadioButton x:Name="StudentPassingBtn" Style="{StaticResource MenuButtonStyle}" Click="Button_Click"/>
    <RadioButton x:Name="StudentReportBtn" Style="{StaticResource MenuButtonTeacherVisibiltyStyle}" Click="Button_Click"/>            
  </StackPanel>
</UserControl>

Примечания
Вы должны настроить / вставить пространства имен XAML, чтобы он скомпилировался.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...