EzDevInfo.com

listbox interview questions

Top listbox frequently asked interview questions

ListBox vs. ListView - how to choose for data binding [closed]

I'm considering either a ListBox or a ListView for a WPF application. It seems either supports data binding and item templates. My application has a simple list of items that I intend to be able to search/sort/filter based on user input. The data binding demo (http://msdn.microsoft.com/en-us/library/ms771319.aspx) uses a ListBox with a CollectionViewSource.

Does anyone have pros/cons for which control to use and when?


Source: (StackOverflow)

Double Click a ListBox item to open a browser

I have a ListBox in my wpf window that binds to an ObervableCollection. I want to open the browser if someone clicks on an element of the ListBox (just like a link). Can someone tell me how to do this? I found something with listboxviews, does it only work this way or is there a way by just using the ListBox?

Yours

Sebastian


Source: (StackOverflow)

Advertisements

Force TextBlock to wrap in WPF ListBox

I have a WPF listbox which displays messages. It contains an avatar on the left side and the username and message stacked vertically to the right of the avatar. The layout is fine until the message text should word wrap, but instead I get a horizontal scroll bar on the listbox.

I've Googled and found solutions to similar issues, but none of them worked.

<ListBox HorizontalContentAlignment="Stretch"  ItemsSource="{Binding Path=FriendsTimeline}">
    <ListBox.ItemTemplate>
        <DataTemplate>
            <StackPanel Orientation="Horizontal">
                <Border BorderBrush="DarkBlue" BorderThickness="3" CornerRadius="2" Margin="3" >
                    <Image Height="32" Width="32"  Source="{Binding Path=User.ProfileImageUrl}"/>
                </Border>
                <StackPanel Orientation="Vertical">
                    <TextBlock Text="{Binding Path=User.UserName}"/>
                    <TextBlock Text="{Binding Path=Text}" TextWrapping="WrapWithOverflow"/> <!-- This is the textblock I'm having issues with. -->
                </StackPanel>
            </StackPanel>
        </DataTemplate>
    </ListBox.ItemTemplate>
</ListBox>

Source: (StackOverflow)

Change selected and unfocused Listbox style to not be grayed out

I have a really simple WPF ListBox with SelectionMode set to Multiple.

<ListBox SelectionMode="Multiple" />

When the ListBox loses focus it's really hard to tell what's been selected because the selection colour changes from blue to a light grey colour. What's the easiest way of changing this behaviour so that it stays blue?

I know it's probably something to do with the ListItem's style, but I can't find where.

Cheers.

Similar: WPF ListView Inactive Selection Color


Source: (StackOverflow)

ListBox with Grid as ItemsPanelTemplate produces weird binding errors

I've got a ListBox control and I'm presenting a fixed number of ListBoxItem objects in a grid layout. So I've set my ItemsPanelTemplate to be a Grid.

I'm accessing the Grid from code behind to configure the RowDefinitions and ColumnDefinitions.

So far it's all working as I expect. I've got some custom IValueConverter implementations for returning the Grid.Row and Grid.Column that each ListBoxItem should appear in.

However I get weird binding errors sometimes, and I can't figure out exactly why they're happening, or even if they're in my code.

Here's the error I get:

System.Windows.Data Error: 4 : Cannot find source for binding with reference 'RelativeSource FindAncestor, AncestorType='System.Windows.Controls.ItemsControl', AncestorLevel='1''. BindingExpression:Path=HorizontalContentAlignment; DataItem=null; target element is 'ListBoxItem' (Name=''); target property is 'HorizontalContentAlignment' (type 'HorizontalAlignment')

Can anybody explain what's going on?

Oh, and, here's my XAML:

<UserControl.Resources>
    <!-- Value Converters -->
    <v:GridRowConverter x:Key="GridRowConverter" />
    <v:GridColumnConverter x:Key="GridColumnConverter" />
    <v:DevicePositionConverter x:Key="DevicePositionConverter" />
    <v:DeviceBackgroundConverter x:Key="DeviceBackgroundConverter" />

    <Style x:Key="DeviceContainerStyle" TargetType="{x:Type ListBoxItem}">
        <Setter Property="FocusVisualStyle" Value="{x:Null}" />
        <Setter Property="Background" Value="Transparent" />

        <Setter Property="Grid.Row" Value="{Binding Path=DeviceId, Converter={StaticResource GridRowConverter}}" />
        <Setter Property="Grid.Column" Value="{Binding Path=DeviceId, Converter={StaticResource GridColumnConverter}}" />

        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="{x:Type ListBoxItem}">
                    <Border CornerRadius="2" BorderThickness="1" BorderBrush="White" Margin="2" Name="Bd"
                            Background="{Binding Converter={StaticResource DeviceBackgroundConverter}}">
                        <TextBlock FontSize="12" HorizontalAlignment="Center" VerticalAlignment="Center" 
                                Text="{Binding Path=DeviceId, Converter={StaticResource DevicePositionConverter}}" >
                            <TextBlock.LayoutTransform>
                                <RotateTransform Angle="270" />
                            </TextBlock.LayoutTransform>
                        </TextBlock>
                    </Border>
                    <ControlTemplate.Triggers>
                        <Trigger Property="IsSelected" Value="true">
                            <Setter TargetName="Bd" Property="BorderThickness" Value="2" />
                            <Setter TargetName="Bd" Property="Margin" Value="1" />
                        </Trigger>
                    </ControlTemplate.Triggers>
                </ControlTemplate>
            </Setter.Value>
        </Setter>            
    </Style>        
</UserControl.Resources>

<Border CornerRadius="3" BorderThickness="3" Background="#FF333333" BorderBrush="#FF333333" >
    <Grid ShowGridLines="False">
        <Grid.RowDefinitions>
            <RowDefinition Height="15" />
            <RowDefinition Height="*" />
        </Grid.RowDefinitions>

        <StackPanel Grid.Row="0" Orientation="Horizontal">
            <Image Margin="20,3,3,3" Source="Barcode.GIF" Width="60" Stretch="Fill" />
        </StackPanel>

        <ListBox ItemsSource="{Binding}" x:Name="lstDevices" Grid.Row="1" 
                 ItemContainerStyle="{StaticResource DeviceContainerStyle}"
                 Background="#FF333333"
                 SelectedItem="{Binding SelectedDeviceResult, ElementName=root, Mode=TwoWay}" >
            <ListBox.ItemsPanel>
                <ItemsPanelTemplate>
                    <Grid>
                        <Grid.LayoutTransform>
                            <RotateTransform Angle="90" />
                        </Grid.LayoutTransform>                            
                    </Grid>
                </ItemsPanelTemplate>
            </ListBox.ItemsPanel>
        </ListBox>
    </Grid>
</Border>


Source: (StackOverflow)

Binding Listbox to List

What's the simplest way to bind a Listbox to a List of objects?


Source: (StackOverflow)

How to scroll to bottom of ListBox?

I am using a Winforms ListBox as a small list of events, and want to populate it so that the last event (bottom) is visible. The SelectionMode is set to none. The user can scroll the list but I would prefer it start out scrolled to the end.

Looking at the lack of support for things like ScrollIntoView, EnsureVisible, I am assuming I will need to create a custom control that inherits from ListBox; however I'm not sure what to do from there.

Some pointers?


Source: (StackOverflow)

A better way of forcing data bound WPF ListBox to update?

I have WPF ListBox which is bound to a ObservableCollection, when the collection changes, all items update their position.

The new position is stored in the collection but the UI does not update. So I added the following:

    void scenarioItems_CollectionChanged(object sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e)
    {
        ToolboxListItem.UpdatePositions();
        lstScenario.ItemsSource = null;
        lstScenario.ItemsSource = ToolboxListItem.ScenarioItems;
        this.lstScenario.SelectedIndex = e.NewStartingIndex;
    }

By setting the ItemsSource to null and then binding it again, the UI is updated,

but this is probably very bad coding :p

Suggestions?


Source: (StackOverflow)

Silverlight 3: ListBox DataTemplate HorizontalAlignment

I have a ListBox with it's ItemTemplate bound to a DataTemplate. My problem is I cannot get the elements in the template to stretch to the full width of the ListBox.

<ListBox x:Name="listPeople" VerticalAlignment="Stretch" HorizontalAlignment="Stretch" 
    Margin="0,0,0,0" Background="{x:Null}" SelectionMode="Extended" Grid.Row="1" 
    ItemTemplate="{StaticResource PersonViewModel.BrowserDataTemplate}" 
    ItemsSource="{Binding Mode=OneWay, Path=SearchResults}" >
</ListBox>

<DataTemplate x:Key="PersonViewModel.BrowserDataTemplate">
   <ListBoxItem HorizontalAlignment="Stretch" VerticalAlignment="Stretch">
     <Grid HorizontalAlignment="Stretch" VerticalAlignment="Stretch" Margin="5,5,5,5">
       <Border Opacity=".1" x:Name="itemBorder"  Background="#FF000000"   
         HorizontalAlignment="Stretch" VerticalAlignment="Stretch" 
         CornerRadius="5,5,5,5" MinWidth="100" Height="50"/>
      </Grid>
   </ListBoxItem>
</DataTemplate>

As you can see, I have added a border within the grid to indicate the width of the template. My goal is to see this border expand to the full width of the listbox. Currently its width is determined by its contents or MinWidth, which is the only thing at the moment keeping it visible at all.


Source: (StackOverflow)

ListBox with ItemTemplate (and ScrollBar!)

I have a databound and itemtemplated ListBox:

<ListBox x:Name="lbLista" 
         ScrollViewer.VerticalScrollBarVisibility="Visible">
    <ListBox.ItemTemplate>
      <DataTemplate>
        <StackPanel Orientation="Horizontal">
          <CheckBox IsChecked="{Binding Deleteable, Mode=TwoWay}" />
          <Label Content="{Binding Name}" />
        </StackPanel>
      </DataTemplate>
    </ListBox.ItemTemplate>
</ListBox>

The ites show fine and they come from an ObservableCollection.

The problem is the scrollbar which appears but is not usable - it does not have a handle to grab. I've tried setting some ScrollView attached properties on ListBox, but they do not affect the situation.


Source: (StackOverflow)

WPF Listbox Show Button in ItemTemplate on MouseOver

I have a listbox containing and image and a button. By default the button is hidden. I want to make the button visible whenever I hover over an item in the listbox. The XAML I am using is below. Thanks

<Window.Resources>
        <Style TargetType="{x:Type ListBox}">
    <Setter Property="ItemTemplate">
                    <Setter.Value>
                        <DataTemplate>
                            <Border BorderBrush="Black" BorderThickness="1" Margin="6">
                                <StackPanel Orientation="Horizontal">
                                    <Image Source="{Binding Path=FullPath}" Height="150" Width="150"/>
                                    <Button x:Name="sideButton" Width="20" Visibility="Hidden"/>
                                </StackPanel>
                            </Border>
                        </DataTemplate>
                    </Setter.Value>
                </Setter>
        </Style>
    </Window.Resources>

Source: (StackOverflow)

How can I sort a ListBox using only XAML and no code-behind?

I need to sort the strings in a ListBox, but it is bound to the view model by another component via the DataContext. So I can't directly instantiate the view model in XAML, as in this example, which uses the ObjectDataProvider.

In my XAML:

<ListBox ItemsSource="{Binding CollectionOfStrings}" />

In my view model:

public ObservableCollection<string> CollectionOfStrings
{
    get { return collectionOfStrings; }
}

In another component:

view.DataContext = new ViewModel();

There is no code behind! So using purely XAML, how would I sort the items in the ListBox? Again, the XAML doesn't own the instantiation of the view model.


Source: (StackOverflow)

WPF ListBox that lays out its items horizontally

I'm trying to write a WPF application for displaying images from a selection. I want to display all of the available images in a banner along the top of the window, and display the main selected image in the main window for further processing.

If I wanted the list on the Left of the window, displaying the images vertically, I can do this quite elegantly using databinding.

    <ListBox 
        Name="m_listBox"
        IsSynchronizedWithCurrentItem="True"
        ItemsSource="{Binding}"            
        >
        <ListBox.ItemTemplate>
            <DataTemplate>
                <Image Source="{Binding}" Width="60" Stretch="Uniform" />
            </DataTemplate>
        </ListBox.ItemTemplate>
    </ListBox>

Is there a straightforward way I can make this horizontal instead of vertical? The main requirements of a solution is:

  • The items are populated using databinding
  • The selected item is changed simply by the user clicking it.

Source: (StackOverflow)

WPF Trigger for IsSelected in a DataTemplate for ListBox items

I have a listbox, and I have the following ItemTemplate for it:

<DataTemplate x:Key="ScenarioItemTemplate">
    <Border Margin="5,0,5,0"
            Background="#FF3C3B3B"
            BorderBrush="#FF797878"
            BorderThickness="2"
            CornerRadius="5">
        <DockPanel>
            <DockPanel DockPanel.Dock="Top"
                       Margin="0,2,0,0">
                <Button HorizontalAlignment="Left"
                        DockPanel.Dock="Left"
                        FontWeight="Heavy"
                        Foreground="White" />
                <Label Content="{Binding Path=Name}"
                       DockPanel.Dock="Left"
                       FontWeight="Heavy"
                       Foreground="white" />
                <Label HorizontalAlignment="Right"
                       Background="#FF3C3B3B"
                       Content="X"
                       DockPanel.Dock="Left"
                       FontWeight="Heavy"
                       Foreground="White" />
            </DockPanel>
            <ContentControl Name="designerContent"
                            Visibility="Collapsed"
                            MinHeight="100"
                            Margin="2,0,2,2"
                            Content="{Binding Path=DesignerInstance}"
                            Background="#FF999898">
            </ContentControl>
        </DockPanel>
    </Border>
</DataTemplate>

As you can see the ContentControl has Visibility set to collapsed.

I need to define a trigger that causes the Visibility to be set to "Visible"

when the ListItem is selected, but I can't figure it out.

Any ideas?

UPDATE: Of course I could simply duplicate the DataTemplate and add triggers to the ListBox in question to use either one or the other, but I want to prevent duplicating this code.


Source: (StackOverflow)

How can I make a column in a listbox in WPF the same width for all items?

I have a ListBox with an ItemTemplate consisting of a TextBlock and a ComboBox. The problem is that the width of the text inside the TextBlock is not the same for each item and the ComboBox controls are not aligned.
How can I set the TextBlock in the template so all items are the same width, that is the one of the widest?

Here is my xaml:

<ListBox MinHeight="100" ItemsSource="{Binding Trainees}">
  <ListBox.ItemTemplate>
    <DataTemplate>
      <Grid Margin="1">
        <Grid.ColumnDefinitions>
          <ColumnDefinition />
          <ColumnDefinition />
        </Grid.ColumnDefinitions>
        <TextBlock VerticalAlignment="Center" Grid.Column="0">
          <TextBlock.Text>
            <MultiBinding StringFormat="{}{0}, {1}">
              <Binding Path="LastName" />
              <Binding Path="FirstName" />
            </MultiBinding>
          </TextBlock.Text>
        </TextBlock>
        <ComboBox HorizontalAlignment="Left" Grid.Column="1"
            ItemsSource="{Binding Source={StaticResource Functions}}" SelectedValue="{Binding Path=Function}"
            MinWidth="100" />
      </Grid>
    </DataTemplate>
  </ListBox.ItemTemplate>
</ListBox>

Source: (StackOverflow)