我们有xaml
:
<ListBox>
<ListBox.ItemsPanel>
<ItemsPanelTemplate>
<UniformGrid IsItemsHost="True" Rows="2"></UniformGrid>
</ItemsPanelTemplate>
</ListBox.ItemsPanel>
</ListBox>
如果窗口的高度为500px
UniformGrid
2 lines
,且700px
3 lines
。如何实现这个?
答案 0 :(得分:1)
有多种可能性。在视图中使用绑定和事件最直接:
public partial class MainWindow : Window, INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
public void OnPropertyChanged(string property = "") => PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(property));
public int Rows { get; private set; } = 3;
public MainWindow()
{
InitializeComponent();
DataContext = this;
}
void ListBox_SizeChanged(object sender, SizeChangedEventArgs e)
{
Rows = ((ListBox)sender).ActualHeight > 700 ? 4 : 3;
OnPropertyChanged(nameof(Rows));
}
}
XAML:
<ListBox SizeChanged="ListBox_SizeChanged">
<ListBox.ItemsPanel>
<ItemsPanelTemplate>
<UniformGrid Rows="{Binding Rows}" />
</ItemsPanelTemplate>
</ListBox.ItemsPanel>
<ListBoxItem>1</ListBoxItem>
<ListBoxItem>2</ListBoxItem>
<ListBoxItem>3</ListBoxItem>
<ListBoxItem>4</ListBoxItem>
<ListBoxItem>5</ListBoxItem>
<ListBoxItem>6</ListBoxItem>
<ListBoxItem>7</ListBoxItem>
<ListBoxItem>8</ListBoxItem>
</ListBox>
调整窗口大小以查看当ListBox
的大小大于700时,它如何在3到4行之间切换。