99// TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH
1010// THE CODE OR THE USE OR OTHER DEALINGS IN THE CODE.
1111// ******************************************************************
12+ using System . Collections . Generic ;
1213using Windows . UI . Xaml ;
1314using Windows . UI . Xaml . Controls ;
1415
@@ -47,17 +48,13 @@ private void RecalculateLayout(double containerWidth)
4748 return ;
4849 }
4950
50- if ( _columns == 0 )
51- {
52- _columns = CalculateColumns ( containerWidth , DesiredWidth ) ;
53- }
54- else
51+ _columns = CalculateColumns ( containerWidth , DesiredWidth ) ;
52+
53+ // If there's less items than there's columns, reduce the column count ;
54+ if ( _listView != null && _listView . Items != null
55+ && _listView . Items . Count > 0 && _listView . Items . Count < _columns )
5556 {
56- var desiredColumns = CalculateColumns ( containerWidth , DesiredWidth ) ;
57- if ( desiredColumns != _columns )
58- {
59- _columns = desiredColumns ;
60- }
57+ _columns = _listView . Items . Count ;
6158 }
6259
6360 ItemWidth = ( containerWidth / _columns ) - 5 ;
@@ -75,6 +72,7 @@ protected override void OnApplyTemplate()
7572 {
7673 _listView . SizeChanged -= ListView_SizeChanged ;
7774 _listView . ItemClick -= ListView_ItemClick ;
75+ _listView . Items . VectorChanged -= ListViewItems_VectorChanged ;
7876 _listView = null ;
7977 }
8078
@@ -83,12 +81,23 @@ protected override void OnApplyTemplate()
8381 {
8482 _listView . SizeChanged += ListView_SizeChanged ;
8583 _listView . ItemClick += ListView_ItemClick ;
84+ _listView . Items . VectorChanged += ListViewItems_VectorChanged ;
8685 }
8786
8887 _isInitialized = true ;
8988 OnOneRowModeEnabledChanged ( this , OneRowModeEnabled ) ;
9089 }
9190
91+ private void ListViewItems_VectorChanged ( Windows . Foundation . Collections . IObservableVector < object > sender , Windows . Foundation . Collections . IVectorChangedEventArgs @event )
92+ {
93+ if ( _listView != null && ! double . IsNaN ( _listView . ActualWidth ) )
94+ {
95+ // If the item count changes, check if more or less columns needs to be rendered,
96+ // in case we were having fewer items than columns.
97+ RecalculateLayout ( _listView . ActualWidth ) ;
98+ }
99+ }
100+
92101 private void ListView_ItemClick ( object sender , ItemClickEventArgs e )
93102 {
94103 var cmd = ItemClickCommand ;
0 commit comments