Lightness Lightness - 1 year ago 79
C# Question

How to implement the visual state in a ListBox

Let's have a


<UniformGrid IsItemsHost="True" Rows="2"></UniformGrid>

If the height of the window to
findings in
2 lines
, and if more then
3 lines
. How to implement this?

Answer Source

There are multiple possibilities. The most straightforward using binding and event in the view:

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()
        DataContext = this;

    void ListBox_SizeChanged(object sender, SizeChangedEventArgs e)
        Rows = ((ListBox)sender).ActualHeight > 700 ? 4 : 3;


<ListBox SizeChanged="ListBox_SizeChanged">
            <UniformGrid Rows="{Binding Rows}" />

Resize the window to see how it switches between 3 and 4 rows once size of ListBox is bigger than 700.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download