WPF中根据IsSelected确定ListBoxItem背景色的问题

smartstar2005 2009-09-24 11:21:55
我想在选择一个Item的时候设定背景色为Yellow,取消选择的时候设定为Green。下面是代码:
    <Window.Resources>
<Converters:ItemBackgroundConverter x:Key="ItemBackgroundConverter"/>

<!--ListBoxItem style -->
<Style TargetType="ListBoxItem">
<Setter Property="SnapsToDevicePixels" Value="true"/>
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="ListBoxItem">
<Border Name="ItemGrid">
<ContentPresenter/>
<Border.Style>
<Style>
<Setter Property="Border.Background" Value="{Binding RelativeSource={RelativeSource TemplatedParent}, Path=IsSelected, Converter={StaticResource ItemBackgroundConverter}}" />
<Setter Property="Border.BorderBrush" Value="Black" />
<Setter Property="Border.BorderThickness" Value="0.5" />
<Setter Property="Border.CornerRadius" Value="4" />
<Setter Property="Border.Margin" Value="2" />
<Setter Property="Border.Padding" Value="4" />
</Style>
</Border.Style>
</Border>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</Window.Resources>
<Grid>
<StackPanel>
<ListBox>
<ListBoxItem>Item1</ListBoxItem>
<ListBoxItem>Item2</ListBoxItem>
<ListBoxItem>Item3</ListBoxItem>
<ListBoxItem>Item4</ListBoxItem>
<ListBoxItem>Item5</ListBoxItem>
<ListBoxItem>Item6</ListBoxItem>
<ListBoxItem>Item7</ListBoxItem>
</ListBox>
</StackPanel>
</Grid>


Converter的代码:

public class ItemBackgroundConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
if (value is Boolean)
{
Boolean blnChecked = (Boolean)value;
if (blnChecked)
{
return Color.FromArgb(0,255,0);
}
else
{
return Color.Green;
}
}

return Color.Green;
}

public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotSupportedException();
}
}


为什么最终的颜色没有改变呢?请大家帮忙看看
...全文
521 2 打赏 收藏 转发到动态 举报
写回复
用AI写文章
2 条回复
切换为时间正序
请发表友善的回复…
发表回复
smartstar2005 2009-09-24
  • 打赏
  • 举报
回复
OK

多谢了!
jv9 2009-09-24
  • 打赏
  • 举报
回复

Public Class MyConverter
Implements IValueConverter
Public Function Convert(ByVal value As Object, ByVal targetType As Type, ByVal parameter As Object, ByVal culture As CultureInfo) As Object Implements IValueConverter.Convert

Dim d As Data = CType(value, Data)
If d.Name.StartsWith("a") Then
Return New SolidColorBrush(Colors.Green)
Else
Return New SolidColorBrush(Colors.Yellow)
End If
End Function
Public Function ConvertBack(ByVal value As Object, ByVal targetType As Type, ByVal parameter As Object, ByVal culture As CultureInfo) As Object Implements IValueConverter.ConvertBack
Return Nothing
End Function
End Class





http://silverlightchina.net/html/developer/2009/0924/192.html

8,735

社区成员

发帖
与我相关
我的任务
社区描述
WPF/Silverlight相关讨论
社区管理员
  • WPF/Silverlight社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧