我有一个WPF窗口,只有一个ComboBox(下拉列表(。如果我选择索引 1(下拉列表中的第二项(,如何扩展该 WPF 窗口以显示更多按钮、文本框等?我是否需要使用选定的索引属性?如果是这样,我如何使窗口在 XAML 中扩展。
我过去曾使用过IValueConverter
来完成此操作。 下面是一个示例转换器:
public class MyConverter : System.Windows.Data.IValueConverter {
public object Convert ( object value , Type targetType , object parameter , CultureInfo culture ) {
if ( value == null )
return System.Windows.Visibility.Hidden;
if ( parameter == null )
return System.Windows.Visibility.Hidden;
if ( value.ToString().Equals ( parameter ) )
return System.Windows.Visibility.Visible;
return System.Windows.Visibility.Hidden;
}
public object ConvertBack ( object value , Type targetType , object parameter , CultureInfo culture ) {
throw new NotImplementedException ( );
}
}
这样做的是,它接受传递给它的值,我期待一个数字,例如项目控件的 SelectedIndex。 然后,我将它与传递的参数进行比较。 如果它们相等,我返回 Visibility.Visible。 在所有其他情况下,我返回 Visibility.Hidden。
现在,你可以像这样使用它并将其插入 XAML:
<Window x:Class="WpfApplication1.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:WpfApplication1"
mc:Ignorable="d"
Title="MainWindow" Height="350" Width="525">
<Window.Resources>
<local:MyConverter x:Key="vConv"/>
</Window.Resources>
<Grid>
<ComboBox x:Name="comboBox" HorizontalAlignment="Left" Margin="25,52,0,0" VerticalAlignment="Top" Width="120">
<ComboBoxItem>Hidden</ComboBoxItem>
<ComboBoxItem>Visible</ComboBoxItem>
</ComboBox>
<Label x:Name="label" Content="Label" HorizontalAlignment="Left" Margin="219,92,0,0" VerticalAlignment="Top" Visibility="{Binding ElementName=comboBox, Path=SelectedIndex, Converter={StaticResource vConv}, ConverterParameter=1, UpdateSourceTrigger=PropertyChanged}"/>
</Grid>
</Window>
您可以看到我们在 Window.Resources 中创建了 MyConverter 类的实例。 当我们在绑定中使用它时,我们可以根据选择的任何索引显示/隐藏我的标签。 现在这是非常基本的,您可以添加很多内容以获得所需的所有功能,但这应该可以帮助您入门。
可以在选择 comboBox 项时使用窗口的 MaxHeight
和 MaxWidth
属性。喜欢这个:
在组合框的选择更改事件上。使用这个
MainWindow obj= new MainWindow();
if(mycombobox.SelectedIndex==0)
{
obj.MaxWidth="600";
obj.MinWidth="600";
}
if(mycombobox.SelectedIndex==1)
{
obj.MaxWidth="200";
obj.MinWidth="200";
}
或者你也可以这样做
if(mycombobox.SelectedIndex==0)
{
this.MaxWidth="600";
this.MinWidth="600";
}
if(mycombobox.SelectedIndex==1)
{
this.MaxWidth="200";
this.MinWidth="200";
}