我是WPF的新手,我想知道是否可以创建一个ListBox可以接受其项目的任何类的PopUp用户控件吗?
我这里有xaml代码,用于“ Tipo”类的对象列表,但是我想将此用户控件用于另一个类,比如说“ Person”类。
<UserControl
...
<UserControl.Resources>
<local:BoolToInvertedBoolConverter x:Key="converter"/>
</UserControl.Resources>
<Grid x:Name="gridPrincipal">
<ToggleButton x:Name="tbTipo" Grid.Row="0" Background="{Binding Path=ColorFondo}" Foreground="{Binding Path=ColorTexto}" Opacity="1" Content="{Binding Path=ContenidoToggleButton}" IsEnabled="{Binding ElementName=Popup1, Path=IsOpen, Converter={StaticResource converter}}" />
<Popup x:Name="Popup1" Grid.Row="0" Grid.Column="1" AllowsTransparency="True" Placement="MousePoint" Focusable="False" StaysOpen="False" PopupAnimation="Slide" PlacementTarget="{Binding ElementName=tbTipo}" IsOpen="{Binding IsChecked, ElementName=tbTipo, Mode=TwoWay}" >
<StackPanel Orientation="Vertical" >
<Grid Margin="0,10,0,0" Background="LightBlue" Height="Auto">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<CheckBox Name="chkTodos" Grid.Column="2" Content="Seleccionar todos" VerticalContentAlignment="Center" MinHeight="25" Margin="0,0,10,0" IsChecked="{Binding SeleccionarTodos}" />
</Grid>
<ScrollViewer VerticalScrollBarVisibility="Auto" HorizontalScrollBarVisibility="Auto" MaxHeight="550" MaxWidth="400" Opacity="0.9">
<Grid Height="Auto" Width="Auto" HorizontalAlignment="Center" VerticalAlignment="Stretch">
<StackPanel Orientation="Vertical" Width="Auto" HorizontalAlignment="Stretch">
<ListBox Name="lbTipo" ItemsSource="{Binding ListTipos, Mode=TwoWay}" Background="LightGray" HorizontalContentAlignment="Stretch" >
<ListBox.ItemTemplate>
<DataTemplate DataType="{x:Type local:Tipo}">
<DataTemplate.Resources>
<SolidColorBrush x:Key="{x:Static SystemColors.HighlightBrushKey}" Color="LightBlue"/>
</DataTemplate.Resources>
<Grid Background="{Binding Path=ColorVigencia}" >
<CheckBox VerticalContentAlignment="Center" IsChecked="{Binding IsChecked}" Focusable="False" Content="{Binding Descripcion}" />
</Grid>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</StackPanel>
</Grid>
</ScrollViewer>
</StackPanel>
</Popup>
</Grid>
</UserControl>
答案 0 :(得分:0)
我想您可以使用数据模板来做到这一点。这样,您只需为ListBox设置ItemsSource,WPF就会根据对象类型确定要使用的数据模板。
这里有一个https://www.tutorialspoint.com/mvvm/mvvm_wpf_data_templates.htm
的例子<UserControl.Resources>
<DataTemplate DataType = "{x:Type data:Student}">
<StackPanel Orientation = "Horizontal">
<TextBox Text = "{Binding Path = FirstName, Mode = TwoWay}"
Width = "100" Margin = "3 5 3 5"/>
<TextBox Text = "{Binding Path = LastName, Mode = TwoWay}"
Width = "100" Margin = "0 5 3 5"/>
<TextBlock Text = "{Binding Path = FullName, Mode = OneWay}"
Margin = "0 5 3 5"/>
</StackPanel>
</DataTemplate>
</UserControl.Resources>
<Grid>
<ListBox ItemsSource = "{Binding Students}"/>
</Grid>