在项目选择上,更改矩形的颜色,该矩形是Windows Phone中ListBoxItem的一部分

时间:2012-06-06 03:55:52

标签: c# windows-phone-7 windows-phone

我有一个带有以下XAML的ListBox:

<ListBox.ItemTemplate>
  <DataTemplate>
    <Grid Name="listItemGrid">
      <Grid.ColumnDefinitions>
        <ColumnDefinition MaxWidth="20" MinWidth="20" Width="20" />
        <ColumnDefinition />
      </Grid.ColumnDefinitions>
      <Rectangle Name="listItemSideBar" Height="85" HorizontalAlignment="Left"
         Margin="0, 0, 0, 0" Stroke="{StaticResource PhoneAccentBrush}" 
         StrokeThickness="1" VerticalAlignment="Top" Fill="{StaticResource
         PhoneAccentBrush}" MinHeight="85" Width="25"/>
      <StackPanel Margin="0,0,0,17" Grid.Column="1" Grid.ColumnSpan="2">
        <TextBlock Name="listItemMainData" Text="{Binding LineTwo}" 
          TextWrapping="NoWrap" Margin="12,0,0,0" Style="{StaticResource 
          PhoneTextExtraLargeStyle}"/>
        <TextBlock Name="listItemSubData" Text="{Binding LineOne}" 
          TextWrapping="NoWrap" Margin="12,-6,0,0" 
          Style="{StaticResource PhoneTextSubtleStyle}"/>
      </StackPanel>
    </Grid>
  </DataTemplate>
</ListBox.ItemTemplate>

当选择ListBoxItem时,我想将ListBoxItem的Rectangle填充颜色更改为不同的颜色;当取消选择ListBoxItem时,我希望填充颜色更改回PhoneAccentBrush。

有没有办法完成这项任务?

1 个答案:

答案 0 :(得分:0)

我终于找到了一个我在下面复制过的解决方案。 ColorHelper类只是从PhoneAccentBrush资源获取PhoneAccentColor。 DarkPhoneAccentColor通过找到的here方法生成。 PropertyValue<string>(child, "Name")是一种语法糖扩展方法,用于从类型的属性中获取值;如果属性不存在,则返回default(T)

尚未对此代码应用完整错误检查。

private void listBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
    Color accent = ColorHelper.PhoneAccentColor;
    Color accentDark = ColorHelper.DarkPhoneAccentColor;
    foreach (object item in e.RemovedItems)
        SetListBoxItemColor(item, accentDark);
    foreach (object item in e.AddedItems)
        SetListBoxItemColor(item, accent);
}

private void SetListBoxItemColor(object item, Color color)
{
    ListBoxItem listBoxItem = listBox.ItemContainerGenerator
        .ContainerFromItem(item) as ListBoxItem;
    if (listBoxItem != null)
    {
        Rectangle rectangle = GetItemsRecursive<Rectangle>(
            listBoxItem, "listItemSideBar");
        SolidColorBrush fillBrush = new SolidColorBrush();
        fillBrush.Color = color;
        rectangle.Fill = fillBrush;
    }
}

private T GetItemsRecursive<T>(DependencyObject lb, string name)
    where T : DependencyObject
{
    int childrenCount = VisualTreeHelper.GetChildrenCount(lb);

    for (int i = 0; i < childrenCount; i++)
    {
        DependencyObject child = VisualTreeHelper.GetChild(lb, i);
        if (child is T)
        {
            string childName = child.GetType().PropertyValue<string>(child, "Name");
            if (String.Compare(childName, name) == 0)
                return (T)child;
        }
        return GetItemsRecursive<T>(child, name);
    }
    return default(T);
}