[英]On item selection, changing the color of a rectangle which is part of a ListBoxItem in 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。
有沒有辦法完成這項任務?
我終於找到了一個解決方案,並在下面進行了復制。 ColorHelper
類僅從PhoneAccentBrush資源獲取PhoneAccentColor。 DarkPhoneAccentColor通過此處找到的方法產生。 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);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.