[英]C# WPF change grid visibility if combobox item is selected
I'm trying to display a Grid
and its contents when an item (anyone) in combobox
is selected. 如果未選擇任何內容,網格將保持隱藏狀態。
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文件
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);
}
<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>
試試
主窗口.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;
}
}
主窗口.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>
或者更類似於您的問題:
主窗口.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;
}
}
主窗口.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 模式
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.