当我选择Grid
中的某个项目(任何人)时,我正在尝试显示combobox
及其内容。如果未选择任何内容,则网格将保持隐藏状态。
XAML
<ComboBox x:Name="cb" HorizontalAlignment="Left" VerticalAlignment="Top" Width="140" Height="25"/>
<Grid x:Name="gr" Visibility="Hidden">
<Border BorderThickness="1" HorizontalAlignment="Left" Height="600" VerticalAlignment="Top" Width="346">
<Border BorderThickness="1" RenderTransformOrigin="0.5,0.5">
</Border>
</Grid>
我试过这个:
XAML.CS
public void ChangeVisibility(ComboBox cb, Grid gr)
{
if (cb.SelectedItem != null)
{
gr.Visibility = Visibility.Visible;
}
else
{
gr.Visibility = Visibility.Hidden;
}
但它没有改变任何东西。即使使用string.IsNullOrEmpty
,我也尝试过多种方式。
combobox
的来源是List<string>
。
修改
这里调用方法
public MainWindow()
{
InitializeComponent();
WindowStartupLocation = WindowStartupLocation.CenterScreen;
ChangeVisibility(cb, gr);
}
答案 0 :(得分:0)
<ComboBox x:Name="cb" HorizontalAlignment="Left" VerticalAlignment="Top" Width="140" Height="25"/>
<Grid x:Name="gr">
<Grid.Style>
<Style TargetType="Grid">
<Setter Property="Visibility" Value="Visible"/>
<Style.Triggers>
<DataTrigger Binding="{Binding ElementName=cb, Path=SelectedItem}" Value="{x:Null}">
<Setter Property="Visibility" Value="Collapsed"/>
</DataTrigger>
</Style.Triggers>
</Style>
</Grid.Style>
<Border BorderThickness="1" HorizontalAlignment="Left" Height="600" VerticalAlignment="Top" Width="346">
<Border BorderThickness="1" RenderTransformOrigin="0.5,0.5">
</Border>
</Grid>
答案 1 :(得分:0)
尝试
<强> MainWindow.xaml.cs 强>
private void ComboBox_Selected(object sender, RoutedEventArgs e)
{
var item = Combo.SelectedItem as ComboBoxItem;
if (item.Content.ToString() == "Visible")
{
RedGrid.Visibility = System.Windows.Visibility.Visible;
}
else
{
RedGrid.Visibility = System.Windows.Visibility.Hidden;
}
}
<强> MainWindow.xaml:强>
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="30"/>
<RowDefinition />
</Grid.RowDefinitions>
<ComboBox Name="Combo" SelectionChanged="ComboBox_Selected">
<ComboBoxItem Content="Visible" />
<ComboBoxItem Content="Hidden" />
</ComboBox>
<Grid Name="RedGrid" Grid.Row="1" Background="Red">
</Grid>
</Grid>
或者更类似于您的问题:
<强> MainWindow.xaml.cs:强>
private void ComboBox_Selected(object sender, RoutedEventArgs e)
{
var item = Combo.SelectedItem as ComboBoxItem;
if (item != null)
{
RedGrid.Visibility = System.Windows.Visibility.Visible;
}
}
<强> MainWindow.xaml:强>
<ComboBox Name="Combo" SelectionChanged="ComboBox_Selected" >
<ComboBoxItem Content="Element 1" />
<ComboBoxItem Content="Element 2" />
</ComboBox>
<Grid Name="RedGrid" Grid.Row="1" Background="Red" Visibility="Hidden">
</Grid>
但我不确定,你的方法是正确的。你不能轻易取消选择ComboBox中的项目,所以基本上如果你选择任何网格将始终可见。我宁愿选择具有多个ComboBoxItem的解决方案,其中一个将是“无”,“隐藏”或类似的那样。
您可以随时考虑WPF框架中非常流行的MVVM模式