我有一个列表框,其中定义了 DataTemplate 。通过视图模型提供 ListBox 的 ItemSource (ListBoxItem)。
我希望当项目数大于5时出现ListBox的滚动查看器。如果有人可以帮助我,我将感到非常高兴。
这是我的代码的一部分:
<ListBox VerticalAlignment="Stretch" Grid.Column="0"
ItemsSource="{Binding Path=Parts, Mode=OneWay}" SelectedIndex="{Binding CurrentPartIndex}"
Height="115" BorderThickness="1" BorderBrush="{DynamicResource {x:Static SystemColors.WindowTextBrush}}">
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal" >
<Label Grid.Column="0" Content="{Binding CurrentLabel, Mode=OneWay}" MinWidth="150" Width="auto" VerticalAlignment="Stretch"/>
<Label Grid.Column="1" Content="{Binding ItemNumber, Mode=OneWay}" MinWidth="50" VerticalAlignment="Stretch"/>
<Label Grid.Column="2" Content="{Binding Cut, Mode=OneWay}" MinWidth="50" VerticalAlignment="Stretch"/>
<Label Grid.Column="3" Content="{Binding Material, Mode=OneWay}" MinWidth="100" VerticalAlignment="Stretch"/>
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
答案 0 :(得分:1)
使用值转换器,以便列表框中的项数控制 ScrollViewer 的可见性。
转换器:
public class CountToVisibility : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
if ((int)value > 5)
return ScrollBarVisibility.Visible;
else
return ScrollBarVisibility.Hidden;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
xaml:
<Window.Resources>
<local:CountToVisibility x:Key="ctv"/>
</Window.Resources>
...
<ListBox VerticalAlignment="Stretch" Grid.Column="0"
ItemsSource="{Binding Path=Parts, Mode=OneWay}" SelectedIndex="{Binding CurrentPartIndex}"
Height="115" BorderThickness="1" BorderBrush="{DynamicResource {x:Static SystemColors.WindowTextBrush}}"
ScrollViewer.HorizontalScrollBarVisibility="{Binding Path=Parts.Count,Converter={StaticResource ctv}}">
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal" >
<Label Grid.Column="0" Content="{Binding CurrentLabel, Mode=OneWay}" MinWidth="150" Width="auto" VerticalAlignment="Stretch"/>
<Label Grid.Column="1" Content="{Binding ItemNumber, Mode=OneWay}" MinWidth="50" VerticalAlignment="Stretch"/>
<Label Grid.Column="2" Content="{Binding Cut, Mode=OneWay}" MinWidth="50" VerticalAlignment="Stretch"/>
<Label Grid.Column="3" Content="{Binding Material, Mode=OneWay}" MinWidth="100" VerticalAlignment="Stretch"/>
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>