有很多人通过元数据编程来提供着色答案,这对于简单的颜色变化来说效果很好。但是,大多数人确实需要根据模型中的数据值进行着色。有人可以提供与 ac# 执行相同操作的示例代码片段吗
<SolidColorBrush x:Key="{x:Static SystemColors.HighlightBrushKey}" color="Red" />
并且可以在这种情况下调用
公共类 MyItem:ListBoxItem { 公共覆盖无效 OnSelected(RoutedEventArgs e){ base.OnSelected(e); 前景 = someBoolean ? Brushes.White:Brushes.Black; Code_To_Coerce_HighlightBrushKey_To_The_Correct_Color(Brushes.Red); } 公共覆盖无效 OnUnSelected(RoutedEventArgs e){ base.OnUnSelected(e); 前景 = someBoolean ? Brushes.Red :Brushes.Black; Code_To_Coerce_HighlightBrushKey_To_The_Correct_Color(SystemColors.WindowBrush); } }
这将是最有帮助的。当然,元数据、XAML 编程让微软可以通过主题和操作系统平台的变化来重新着色或“改变”关于着色的大部分内容。但这不适用于需要以不同方式为每个 ListBoxItem 着色的应用程序,包括选择背景和前景更改。
更新:
可以使用以下代码
public class SiteDataItem : ListBoxItem {
SiteInfo site;
protected override void OnUnselected( RoutedEventArgs e ) {
base.OnUnselected(e);
Foreground = site.Enabled ? Brushes.Black : Brushes.Red;
Style s = new Style(typeof(ListBox));
theSiteList.Style = s;
}
protected override void OnSelected( RoutedEventArgs e ) {
base.OnSelected(e);
Foreground = site.Enabled ? Brushes.White : Brushes.White;
if( site.Enabled == false ) {
Style s = new Style(typeof(ListBox));
s.Resources.Add(SystemColors.HighlightBrushKey, Brushes.Red);
theSiteList.Style = s;
}
}
}
以编程方式影响样式更改,选择和取消选择,并获得所需的行为。我现在想了解的是如何与 XAML 的触发器和属性相关联,以驱动这种行为,而不仅仅是在列表框模型中包含数据。