如何设置ListBox项的前景色

nzm*_*ike 3 listbox colors windows-phone-7

我在WP7应用程序页面中有一个ListBox,它绑定到名为Location的自定义对象的集合(List).在该对象中是一个名为WMO的字段,当ListBox加载时我想要做的是设置任何绑定列表框项目的foregound颜色与我的默认值具有相同的值...但我似乎无法让这个工作我读过或谷歌搜索没有任何帮助.

我知道列表中的项目绑定到数据源但我想要获得该项目的物理表示并更改前景颜色....只是无法弄清楚我是如何做到的,所以如果有人可以帮助我'我很欣赏它.

<Grid x:Name="ContentPanel" Grid.Row="1" Margin="0,0,0,0" >
    <ScrollViewer Height="615"  HorizontalAlignment="Left" Margin="5,5,5,5" Name="scrollViewer1" VerticalAlignment="Top">
        <ListBox Name="lbxSavedLocs" Height="615" FontSize="22" HorizontalAlignment="Left" VerticalAlignment="Top" Width="470" SelectionChanged="lbxSavedLocs_SelectionChanged" Loaded="lbxSavedLocs_Loaded">
            <ListBox.ItemTemplate>
                <DataTemplate>
                    <StackPanel Orientation="Horizontal">
                        <TextBlock Width="380" Text="{Binding SiteName}" HorizontalAlignment="Left" />
                        <TextBlock Width="90" Text="{Binding WMO}" HorizontalAlignment="Center" />
                    </StackPanel>
                </DataTemplate>
            </ListBox.ItemTemplate>
        </ListBox>
    </ScrollViewer>
</Grid>
Run Code Online (Sandbox Code Playgroud)
private void lbxSavedLocs_Loaded(object sender, RoutedEventArgs e)
{
    //Populate the listbox from our saved locations.
    lbxSavedLocs.ItemsSource = gl.savedLocs.OrderBy(x => x.SiteName);

    foreach (Location itm in lbxSavedLocs.Items)
    {
        if (loc.WMO == gl.defaultWMO)
        {
          //GET AN "INVALID CAST" EXCEPTION HERE:
          ((ListBoxItem)itm).Foreground  = new SolidColorBrush(Color.FromArgb(255, 255, 255, 255));
        }
    }

    //Hopefully this produces a redraw of the ListBox.
    lbxSavedLocs.InvalidateArrange();
}
Run Code Online (Sandbox Code Playgroud)

Bor*_*ska 6

试试这个:

选项1:

 ListBoxItem lbi1 = (ListBoxItem)(listBox.ItemContainerGenerator.ContainerFromIndex(0));
lbi1.Foreground= new SolidColorBrush(Color.FromArgb(100, 45, 23, 45));
Run Code Online (Sandbox Code Playgroud)

选项2:

ListBoxItem lbi2 = (ListBoxItem)(listBox.ItemContainerGenerator.ContainerFromItem(listBox.Items.SelectedItem));

 lbi2.Foreground= new SolidColorBrush(Colors.Red);
Run Code Online (Sandbox Code Playgroud)