I have an issue with getting the value (text) from ListView selected item.
Besides, I am not using MVVM, it is powershell runspace.
Here is the XAML code:
<Window x:Class="Post_Depl_App.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:Post_Depl_App"
mc:Ignorable="d"
Title="Post_Depl_App" WindowState="Maximized" ResizeMode="NoResize" WindowStartupLocation="CenterScreen" Topmost="false" Background="#0060a9">
<Window.Resources>
<BooleanToVisibilityConverter x:Key="b2v" />
<Style x:Key="FocusTextBox" TargetType="Grid">
<Style.Triggers>
<DataTrigger Binding="{Binding ElementName=NumText, Path=IsVisible}" Value="True">
<Setter Property="FocusManager.FocusedElement" Value="{Binding ElementName=NumText}"/>
</DataTrigger>
</Style.Triggers>
</Style>
</Window.Resources>
<Grid>
<ListView Name="SiteList" Height="530" Width="700" HorizontalAlignment="Center" Margin="0,350,0,100" Background="Transparent" BorderThickness="0" VerticalAlignment="Top"
Foreground="White" FontFamily="Segoe UI SemiLight" FontSize="20"
VirtualizingStackPanel.IsVirtualizing="True" ItemsSource="{Binding}" ScrollViewer.VerticalScrollBarVisibility="Hidden" ScrollViewer.CanContentScroll="False" ScrollViewer.IsDeferredScrollingEnabled="True"
SelectedIndex="0">
<ListViewItem Content = "Australia"></ListViewItem>
<ListViewItem Content = "Chile"></ListViewItem>
</ListView>
And here is the powershell where I have troubles. Probably finding the right property:
$SiteCheck = $SyncHash.Window.Dispatcher.invoke([System.Func[String]{$SyncHash.SiteList.SelectedItem.ToString()})
if($SiteCheck -eq "Australia"){
(Get-Content -path C:\Post_Setup\temp.txt -Raw) -replace 'SiteVar','AU' | Set-Content -Path C:\Post_Setup\temp.txt
}
elseif($SiteCheck -eq "Chile"){
(Get-Content -path C:\Post_Setup\temp.txt -Raw) -replace 'SiteVar','CL' | Set-Content -Path C:\Post_Setup\temp.txt
}
I suppose the issue lies in this line:
$SiteCheck = $SyncHash.Window.Dispatcher.invoke([System.Func[String]{$SyncHash.SiteList.SelectedItem.ToString()})
It doesn't work for ListView or ListBox.
However this works perfectly for ComboBox:
$SiteCheck = $SyncHash.Window.Dispatcher.invoke([System.Func[String]{$SyncHash.SiteBox.Text})
Does anybody know the best way to get selected item value as a text from ListView/Box?
Thank you.
In your case the type of SelectedItem is ListViewItem. You need to get a value of ListViewItem.Content property.
You can specify SelectedValuePath which is the path (property name) in SelectedItem used to get the SelectedValue.
<ListView Name="SiteList" Height="530" Width="700" HorizontalAlignment="Center" Margin="0,350,0,100" Background="Transparent" BorderThickness="0" VerticalAlignment="Top"
Foreground="White" FontFamily="Segoe UI SemiLight" FontSize="20"
VirtualizingStackPanel.IsVirtualizing="True" ItemsSource="{Binding}" ScrollViewer.VerticalScrollBarVisibility="Hidden" ScrollViewer.CanContentScroll="False" ScrollViewer.IsDeferredScrollingEnabled="True"
SelectedIndex="0" SelectedValuePath="Content">
<ListViewItem Content = "Australia"></ListViewItem>
<ListViewItem Content = "Chile"></ListViewItem>
</ListView>
Now the SelectedValue contains value of ListViewItem.Content, so read it in the PowerShell.
$SiteCheck = $SyncHash.Window.Dispatcher.invoke([System.Func[String]{$SyncHash.SiteList.SelectedValue.ToString()})
Related
In a WPF application and using the Fluent Ribbon Control Suite, I have a DropDownButton that opens up a Gallery that lets the user select a color.
Here is the XAML that creates the button:
<Fluent:DropDownButton x:Name="btnCommentColor" Header="Comments">
<Fluent:DropDownButton.Icon>
<!-- What goes here? -->
</Fluent:DropDownButton.Icon>
<Fluent:Gallery x:Name="galCommentColor" ItemsSource="{Binding Source={StaticResource colorPropertiesOdp}}" SelectedValuePath="Name" MaxItemsInRow="12">
<Fluent:Gallery.ItemTemplate>
<DataTemplate>
<Border BorderThickness="1" CornerRadius="2" BorderBrush="Black" Width="25" Height="25" VerticalAlignment="Stretch" Background="{Binding Name}" />
</DataTemplate>
</Fluent:Gallery.ItemTemplate>
</Fluent:Gallery>
</Fluent:DropDownButton>
The SelectedItem of the Gallery returns the Name of the color. I want to make the Icon of the button display the actual color that was selected. Can this be done purely with XAML? I have been trying various things found online but so far have been unable to get anything other than the color name to appear where I want the color rectangle to go. Look for the "What Goes Here?" in the XAML above.
I appreciate any helpful suggestions. Thanks for reading!
UPDATE:
I tried the answer given below and it still doesn't work. I must have something wrong. Here's an updated listing of all the XAML code for this button. Take a look at the XAML for the Gallery itself and the binding for the SolidColorBrush and tell me if you see what i've done wrong.
<Window.Resources>
<ObjectDataProvider MethodName="GetType"
ObjectType="{x:Type sys:Type}" x:Key="colorsTypeOdp">
<ObjectDataProvider.MethodParameters>
<sys:String>System.Windows.Media.Colors, PresentationCore,
Version=3.0.0.0, Culture=neutral,
PublicKeyToken=31bf3856ad364e35</sys:String>
</ObjectDataProvider.MethodParameters>
</ObjectDataProvider>
<ObjectDataProvider ObjectInstance="{StaticResource colorsTypeOdp}"
MethodName="GetProperties" x:Key="colorPropertiesOdp">
</ObjectDataProvider>
</Window.Resources>
<Fluent:DropDownButton Name="btnCommentColor" Header="Comments">
<Fluent:DropDownButton.LargeIcon>
<Grid Width="32" Height="32">
<Image Source="Icons\BlueLarge.png" />
<Border Height="32" VerticalAlignment="Bottom" BorderThickness="0" CornerRadius="2">
<Border.Background>
<SolidColorBrush Color="{Binding ElementName=galCommentColor, Path=SelectedValue, FallbackValue=Green}" />
</Border.Background>
</Border>
</Grid>
</Fluent:DropDownButton.LargeIcon>
<Fluent:Gallery Name="galCommentColor" ItemsSource="{Binding Source={StaticResource colorPropertiesOdp}}" SelectedValuePath="Name" MaxItemsInRow="12">
<Fluent:Gallery.ItemTemplate>
<DataTemplate>
<Border ToolTip="{Binding Path=Name}" BorderThickness="1" CornerRadius="2" BorderBrush="Black" Width="25" Height="25" VerticalAlignment="Stretch" Background="{Binding Name}" />
</DataTemplate>
</Fluent:Gallery.ItemTemplate>
</Fluent:Gallery>
</Fluent:DropDownButton>
On the page 17 of the walkthrough you have an example of what you are trying to achieve.
You can download it here : http://fluent.codeplex.com/documentation
Taken from the walkthrough :
<fluent1:Ribbon>
<fluent1:Ribbon.Menu>
<fluent1:Backstage />
</fluent1:Ribbon.Menu>
<fluent1:RibbonTabItem Header="Home">
<fluent1:RibbonGroupBox Header="Clipboard">
<!-- The following code shows standard mode for color gallery -->
<fluent1:DropDownButton Header="Standard">
<!-- It's possible to create custom icon to present selected color -->
<fluent1:DropDownButton.Icon>
<Grid Width="16" Height="16">
<Image Source="Images\FontColor.png" />
<Border Height="4"
VerticalAlignment="Bottom"
BorderThickness="0">
<Border.Background>
<SolidColorBrush
Color="{Binding ElementName=ColorGalleryStandard, Path=SelectedColor, FallbackValue=Black}" />
</Border.Background>
</Border>
</Grid>
</fluent1:DropDownButton.Icon>
<fluent1:ColorGallery x:Name="ColorGalleryStandard"
IsNoColorButtonVisible="False"
SelectedColor="Red" />
<fluent1:MenuItem Header="A Menu Item" Icon="Images\Pink.png" />
</fluent1:DropDownButton>
</fluent1:RibbonGroupBox>
</fluent1:RibbonTabItem>
</fluent1:Ribbon>
UPDATE
I see nothing wrong in your code, I've pasted it and it ran successfully, here is it again pasted from my working test.
<Window x:Class="WpfApplication8.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:fluent1="clr-namespace:Fluent;assembly=Fluent"
xmlns:system="clr-namespace:System;assembly=mscorlib"
Title="MainWindow"
Width="525"
Height="350">
<Window.Resources>
<ObjectDataProvider x:Key="colorsTypeOdp"
MethodName="GetType"
ObjectType="{x:Type system:Type}">
<ObjectDataProvider.MethodParameters>
<system:String>
System.Windows.Media.Colors, PresentationCore,
Version=3.0.0.0, Culture=neutral,
PublicKeyToken=31bf3856ad364e35
</system:String>
</ObjectDataProvider.MethodParameters>
</ObjectDataProvider>
<ObjectDataProvider x:Key="colorPropertiesOdp"
MethodName="GetProperties"
ObjectInstance="{StaticResource colorsTypeOdp}" />
</Window.Resources>
<fluent1:DropDownButton Name="btnCommentColor" Header="Comments">
<fluent1:DropDownButton.LargeIcon>
<Grid Width="32" Height="32">
<Image Source="Icons\BlueLarge.png" />
<Border Height="32"
VerticalAlignment="Bottom"
BorderThickness="0"
CornerRadius="2">
<Border.Background>
<SolidColorBrush
Color="{Binding ElementName=galCommentColor, Path=SelectedValue, FallbackValue=Green}" />
</Border.Background>
</Border>
</Grid>
</fluent1:DropDownButton.LargeIcon>
<fluent1:Gallery Name="galCommentColor"
ItemsSource="{Binding Source={StaticResource colorPropertiesOdp}}"
MaxItemsInRow="12"
SelectedValuePath="Name">
<fluent1:Gallery.ItemTemplate>
<DataTemplate>
<Border Width="25"
Height="25"
VerticalAlignment="Stretch"
Background="{Binding Name}"
BorderBrush="Black"
BorderThickness="1"
CornerRadius="2"
ToolTip="{Binding Path=Name}" />
</DataTemplate>
</fluent1:Gallery.ItemTemplate>
</fluent1:Gallery>
</fluent1:DropDownButton>
</Window>
Thanks to Aybe for confirming that it's not me. I did get the result I wanted by using a converter on the LargeIcon property of the DropDownButton.
Here's the XAML:
<Fluent:DropDownButton Name="btnCommentColor" Header="Comments" HasTriangle="False" LargeIcon="{Binding ElementName=galCommentColor, Path=SelectedValue, Converter={StaticResource ColorNameToBorderConverter_Key}}">
<Fluent:Gallery x:Name="galCommentColor" ItemsSource="{Binding Source={StaticResource colorPropertiesOdp}}" SelectedValuePath="Name" MaxItemsInRow="12" SelectedIndex="51">
<Fluent:Gallery.ItemTemplate>
<DataTemplate>
<Border ToolTip="{Binding Name}" BorderThickness="1" CornerRadius="2" BorderBrush="Black" Width="25" Height="25" VerticalAlignment="Stretch" Background="{Binding Name}" />
</DataTemplate>
</Fluent:Gallery.ItemTemplate>
</Fluent:Gallery>
</Fluent:DropDownButton>
And the code:
Public Class ColorNameToBorderConverter
Implements IValueConverter
Public Function Convert(value As Object, targetType As Type, parameter As Object, culture As Globalization.CultureInfo) As Object Implements IValueConverter.Convert
If ApplicationIsInDesignMode Then value = "Black"
If TypeOf value Is String Then
Return New Border With {
.Height = 32,
.BorderThickness = New Thickness(1),
.BorderBrush = New SolidColorBrush(System.Windows.Media.Colors.Black),
.CornerRadius = New CornerRadius(2, 2, 2, 2),
.VerticalAlignment = VerticalAlignment.Bottom,
.Background = New SolidColorBrush(ColorConverter.ConvertFromString(value))
}
Else
Throw New InvalidOperationException("Unsupported type [" & value.GetType.ToString & "]")
End If
End Function
Public Function ConvertBack(value As Object, targetType As Type, parameter As Object, culture As Globalization.CultureInfo) As Object Implements IValueConverter.ConvertBack
Throw New NotImplementedException
End Function
Private Shared ReadOnly Property ApplicationIsInDesignMode() As Boolean
Get
Return CBool(DesignerProperties.IsInDesignModeProperty.GetMetadata(GetType(DependencyObject)).DefaultValue)
End Get
End Property
End Class
I've seen similar questions, but I still not able to do my need. I need to output checkbox's name through a label inside a user control:
Window1.xaml:
<Window x:Class="WpfBinding.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:WpfBinding" Title="Window1" Height="300" Width="300">
<Grid>
<CheckBox Name="checkBox1">
<local:UserControl1></local:UserControl1>
</CheckBox>
</Grid>
</Window>
UserControl1.xaml:
<UserControl x:Class="WpfBinding.UserControl1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<Canvas>
<Label Content="{Binding ElementName=checkBox1, Path=Name}"></Label>
</Canvas>
</UserControl>
How to do it correctly? What lack of knowledge I have? Thanks for help.
Above solution will work, but a more direct solution for this specific problem would be to use RelativeSource binding in your user control as below:
<Canvas>
<Label Content="{Binding RelativeSource={RelativeSource AncestorType=CheckBox, AncestorLevel=1}, Path=Name}"></Label>
</Canvas>
Hope this is what you need !!!
ElementName binding works within in same XAML scope. This will work -
<Grid>
<CheckBox Name="checkBox1"/>
<Label Content="{Binding ElementName=checkBox1, Path=Name}"/>
</Grid>
But if you want to do it in different UserControl, you have to tweak a bit your code and use Tag to hold name -
<Grid>
<CheckBox Name="checkBox1">
<local:UserControl1 Tag="{Binding ElementName=checkBox1, Path=Name}"/>
</CheckBox>
</Grid>
UserControl.xaml
<Canvas>
<Label Content="{Binding Path=Tag, RelativeSource={RelativeSource
Mode=FindAncestor, AncestorType=UserControl}}"/>
</Canvas>
On a sidenote, in your UserControl, you know you need to bind with ElementName = checkBox1 and that's the name only you are binding to. Its something equivalent to -
<Label Content="checkBox1"/>
I'm trying to use the RadDiagram commands from a separate window. My bindings don't work because "Cannot find source for binding with reference 'ElementName=Diagram'". My (simplified) XAML looks like this:
<UserControl x:Class="Client.Wpf.EditableLayoutControl"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:telerik="http://schemas.telerik.com/2008/xaml/presentation"
xmlns:s="clr-namespace:Client.Wpf" xmlns:Converters="clr-namespace:Client.Wpf.Converters"
mc:Ignorable="d" DataContext="{Binding RelativeSource={RelativeSource Self}}"
d:DesignHeight="300" d:DesignWidth="800" Background="Transparent" Name="Root">
<UserControl.Resources>
<Converters:MultiBoolToVisibilityConverter x:Key="multiBoolToVis"/>
<Converters:ObjectToBooleanConverter x:Key="objToBool"/>
<telerik:InvertedBooleanConverter x:Key="invBool"/>
</UserControl.Resources>
<telerik:RadDocking HasDocumentHost="False" BorderThickness="0" Name="DockingStation">
<telerik:RadSplitContainer>
<telerik:RadPaneGroup>
<telerik:RadPane CanDockInDocumentHost="False" Title="Controls" >
<telerik:RadPane.TitleTemplate>
<DataTemplate>
<Grid Margin="0 5">
<ContentPresenter Content="{Binding}" VerticalAlignment="Center"/>
<telerik:RadButton Command="telerik:DiagramCommands.Undo" CommandTarget="{Binding Path=Diagram, Source={RelativeSource FindAncestor, AncestorType={x:Type s:EditableLayoutControl}}}" />
</Grid>
</DataTemplate>
</telerik:RadPane.TitleTemplate>
<telerik:RadTabControl ...></telerik:RadTabControl>
</telerik:RadPane>
</telerik:RadPaneGroup>
</telerik:RadSplitContainer>
<telerik:RadSplitContainer>
<telerik:RadPaneGroup>
<telerik:RadPane PaneHeaderVisibility="Collapsed" HorizontalAlignment="Stretch" HorizontalContentAlignment="Stretch">
<Grid>
<telerik:RadDiagram Name="Diagram">...
</telerik:RadDiagram>
</Grid>
</telerik:RadPane>
</telerik:RadPaneGroup>
</telerik:RadSplitContainer>
</telerik:RadDocking>
</UserControl>
The problematic line of code is this beaut from inside the DataTemplate:
CommandTarget="{Binding Path=Diagram, Source={RelativeSource FindAncestor, AncestorType={x:Type s:EditableLayoutControl}}}"
That line of code doesn't work because Diagram is not a property, and bindings require properties. Using ElementName instead of Path there also doesn't work as ElementName and Source are exclusive. I also tried this:
CommandTarget="{Binding ElementName=Diagram}"
That line of code doesn't work. It gives this error:
System.Windows.Data Error: 4 : Cannot find source for binding with reference 'ElementName=Diagram'. BindingExpression:(no path); DataItem=null; target element is 'RadButton' (Name=''); target property is 'CommandTarget' (type 'IInputElement')
I also tried CommandTarget="{x:Reference Diagram}", but that feature is apparently not yet implemented in .NET 4.0. How is it done?
In this particular situation I had to set the Loaded event on the undo button. Then in my event handler (code-behind) I did this: ((RadButton)e.Source).CommandTarget = Diagram;.
The problem is that RelativeSource does not work in the following case. I use silverlight 5.
//From MainPage.xaml
<Grid x:Name="LayoutRoot" Background="White" Height="100" Width="200">
<Popup IsOpen="True">
<TextBlock Text="{Binding Path=DataContext, RelativeSource={RelativeSource AncestorType=Grid}}" />
</Popup>
</Grid>
//From MainPage.xaml.cs
public MainPage()
{
InitializeComponent();
DataContext = "ololo";
}
If I set a breakpoint on the binding, I'll get Error:
System.Exception: BindingExpression_CannotFindAncestor.
If I use ElementName=LayoutRoot instead of RelativeSource, everything will be OK.
Why does the relative source binding not work?
Popup is like ContextMenu , ToolTip controls , They are not added to the VisualTree. For this you will have to do like
<Grid x:Name="LayoutRoot" Height="100" Width="200" Background="Black">
<Popup Grid.Row="0" x:Name="popup" DataContext="{Binding PlacementTarget.DataContext, RelativeSource={RelativeSource Mode=Self}}">
<TextBlock Text="{Binding DataContext, ElementName=popup}" Background="Red" Width="30" Height="30" />
</Popup>
</Grid>
public MainWindow()
{
InitializeComponent();
DataContext = "abcd";
popup.PlacementTarget = LayoutRoot;
}
I hope this will help.Not like in case of ContextMenu or Tooltip , here you will also have to specify the PlacementTarget.
You can make small hack: setup DataContext via resources.
<Grid.Resources>
<Style TargetType="TextBlock">
<Setter Property="DataContext" Value="{Binding ElementName=myGrid, Path=DataContext}" />
</Style>
</Grid.Resources>
As others have mentioned, it's because the Popup is not part of the visual tree. Instead, you can use the Popup's PlacementTarget property to get back to the visual tree:
<Grid x:Name="LayoutRoot" Background="White" Height="100" Width="200">
<Popup IsOpen="True">
<TextBlock Text="{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type Popup}},
Path=PlacementTarget.DataContext}" />
</Popup>
</Grid>
Popups are not part of the visual tree.
Relative Source "Gets or sets the binding source by specifying its location relative to the position of the binding target (MSDN)". Since Popups are not part of the visual tree of the control that is showing it, it will not be able to resolve anything outside of the popup.
from this question, I drilled down the problem to a listbox, that doesn't resize, when the Listbox-Items shrink. It resizes accordingly, when the size of the items grow, but it doesn't shrink, when the size of the items decrease.
The items can grow/shrink because the items containing textboxes, that resize with the input.
Jeremiah suggested to start a new question with more code to show, so here we go:
Our evil listbox is part of a UserControl, that contains a StackPanel with a Label (HorizontalAlignment=Center), the listbox (HA=Left) and a Button (HA=Right). The listbox-items are datalinked to an ObservableCollection
You will recognize beautiful BackgroundColors on the ListBox and the ListBoxItems. I used them to be able to tell wheter the Items or the Listbox itself doesn't shrink. I found out, that the Items shrink, but the Listbox doesn't.
Ok, here is the code of my UserControl:
<StackPanel VerticalAlignment="Top" HorizontalAlignment="Left">
<StackPanel.Background>
<SolidColorBrush Color="{StaticResource ColorBasicDark}"/>
</StackPanel.Background>
<sdk:Label x:Name="LabelServiceName" FontSize="{StaticResource FontSizeMedium}" Margin="2" HorizontalAlignment="Center" Content="LabelServiceName">
<sdk:Label.Foreground>
<SolidColorBrush Color="{StaticResource ColorBasicLight}"/>
</sdk:Label.Foreground>
</sdk:Label>
<ListBox x:Name="ListBoxCharacteristics" BorderBrush="{x:Null}" Margin="0" HorizontalContentAlignment="Left" FontSize="9.333" HorizontalAlignment="Left">
<ListBox.Foreground>
<SolidColorBrush Color="{StaticResource ColorBasicLight}"/>
</ListBox.Foreground>
<!-- DataTemplate to display the content -->
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel x:Name="StackPanelBorder" Orientation="Horizontal" HorizontalAlignment="Left">
<TextBox x:Name="TextBoxCharacteristicName" Style="{StaticResource InputTextBox}" Text="{Binding Name}" />
<TextBox x:Name="TextBoxSep" Style="{StaticResource ReadOnlyTextBox}" Text="=" />
<TextBox x:Name="TextBoxFuncOrValue" Style="{StaticResource InputTextBox}" Text="{Binding Value.Text}" />
<TextBox x:Name="TextBoxValue" Style="{StaticResource ReadOnlyTextBox}" />
<Button x:Name="ButtonRemove" Style="{StaticResource BasicButtonStyle}" Content="-" Click="ButtonRemove_Click" />
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
<ListBox.ItemContainerStyle>
<Style TargetType="ListBoxItem">
<Setter Property="HorizontalAlignment" Value="Left" />
<Setter Property="Background" Value="Yellow" />
</Style>
</ListBox.ItemContainerStyle>
<ListBox.Background>
<SolidColorBrush Color="Red" />
</ListBox.Background>
</ListBox>
<Button x:Name="ButtonAddCharaDisplayObject" Style="{StaticResource BasicButtonStyle}" Content="+" HorizontalAlignment="Right" Click="ButtonAddCharaDisplayObject_Click" />
</StackPanel>
I have no idea why the listbox doesn't shrink when the size of the items shrink, although I have set the listbox' size to Auto and HorizontalAlignment to Left
Thanks in advance,
Frank
I finally found the solution in this post. The problem is, that from Silverlight 3 on, the ListBox uses VirtualizationStackPanel to display the ListItems. Other than StackPanel, VirtualizationStackPanel uses all the space it gets and never gives it back. So, when the biggest item in your list shrinks and therefor the ListBox itself could shrink because now there is unused space, the ListBox' width (and height for that matter) will still stay the same because of VirtualizationStackPanel doesn't shrink properly.
To fix this, we can force the ListBox to use StackPanel instead of VirtualizationStackPanel. Note, that this may come at the cost of performance!
<ListBox HorizontalContentAlignment="Left" FontSize="9.333" HorizontalAlignment="Left">
... // other listbox related stuff
<ListBox.ItemsPanel>
<ItemsPanelTemplate>
<StackPanel />
</ItemsPanelTemplate>
</ListBox.ItemsPanel>
</ListBox>
Well... I don't have all of your code. But, I simplified what you had above to this and it works.
I hope this will help you, in some way, figure out your problem. Once again, it could be the parent of this control causing the problems. It could also be one of your styles you are applying. Try stripping out EVERYTHING from your control that doesn't have to be there, then add it back slowly to find the culprit.
I created a new silverlight application, and this is literally the only thing in it. The listbox grows and shrinks as expected.
XAML:
<UserControl
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"
x:Class="Test.MainPage">
<Grid x:Name="LayoutRoot">
<StackPanel VerticalAlignment="Top" HorizontalAlignment="Left">
<StackPanel.Background>
<SolidColorBrush Color="Black"/>
</StackPanel.Background>
<ListBox x:Name="ListBox" BorderBrush="{x:Null}" Margin="0" HorizontalContentAlignment="Left" FontSize="9.333" HorizontalAlignment="Left">
<ListBox.Foreground>
<SolidColorBrush Color="Silver"/>
</ListBox.Foreground>
<!-- DataTemplate to display the content -->
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanelOrientation="Horizontal" HorizontalAlignment="Left">
<TextBox FontSize="30" Text="{Binding}" />
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
<ListBox.ItemContainerStyle>
<Style TargetType="ListBoxItem">
<Setter Property="HorizontalAlignment" Value="Left" />
<Setter Property="Background" Value="Yellow" />
</Style>
</ListBox.ItemContainerStyle>
<ListBox.Background>
<SolidColorBrush Color="Red" />
</ListBox.Background>
</ListBox>
<StackPanel Orientation="Horizontal" HorizontalAlignment="Right" Height="30">
<Button Content="Add" Click="Add_Click" Width="100"/>
<Button Content="Remove" Click="Remove_Click" Width="100"/>
</StackPanel>
</StackPanel>
</Grid>
</UserControl>
Code Behind:
using System;
using System.Windows;
using System.Windows.Controls;
namespace Test
{
public partial class MainPage : UserControl
{
public MainPage()
{
// Required to initialize variables
InitializeComponent();
Count = 8;
}
private int Count;
private void Add_Click(object sender, System.Windows.RoutedEventArgs e)
{
Count = Count * 8;
ListBox.Items.Add("Hi Mom (" + Count.ToString() + ")");
}
private void Remove_Click(object sender, System.Windows.RoutedEventArgs e)
{
ListBox.Items.RemoveAt(ListBox.Items.Count-1);
}
}
}