简体   繁体   English

如何从后面的代码更改列表框未选择的项目颜色

[英]How to change a listbox unselected item colour from code behind

I have to create listBox via code behind. 我必须通过后面的代码创建listBox。 After that I have to change the colour that the selected item has when the listbox is not selected. 之后,当未选择列表框时,我必须更改所选项目的颜色。 I have found that solution but am not able to render it via code behind. 我已经找到解决方案,但是无法通过后面的代码来呈现它。

在此处输入图片说明

Thank you 谢谢

As you've already seen the answer as in the link, you need to apply a style. 正如您已经在链接中看到答案一样,您需要应用样式。 Now You need help applying that style (defined in XAML) via code behind? 现在,您需要通过后面的代码来应用该样式(在XAML中定义)的帮助吗? If yes then apply the below code: 如果是,则应用以下代码:

Style style = this.FindResource("YourStyleName") as Style;
myListBox.Style = style;

The above code works if your style is defined in the same Window's XAML. 如果您的样式是在同一Window的XAML中定义的,则上面的代码将起作用。 If it's somewhere else, follow the below code: 如果在其他地方,请遵循以下代码:

Style style = Application.Current.FindResource("YourStyleName") as Style;
myListBox.Style = style;

That being said, I would not recommend adding a listbox via C# as it can be tough to handle UI via C#. 话虽如此,我不建议通过C#添加一个listbox ,因为通过C#处理UI可能很困难。 I would recommend defining listbox in XAML and using databinding , INotifyPropertyChanged to reduce your code complexity. 我建议在XAML中定义列表框,并使用databindingINotifyPropertyChanged来降低代码复杂度。

I hope I've answered your question. 希望我已经回答了您的问题。 let me know if there is anything else in the comments section. 让我知道评论部分是否还有其他内容。

Also, please note: in the question the link you've mentioned. 另外,请注意:在问题中您提到的链接。 exactly like that the style will go in the XAML 完全一样,样式将在XAML中使用

Very easy if it's ok for you overriding the windows colour on the listbox 如果可以的话,可以很容易地覆盖列表框上的窗口颜色

listBox1.Resources[SystemColors.InactiveSelectionHighlightBrushKey] = Brushes.Blue;

I picked your rgb colour so to be precise it's: 我选择了您的rgb颜色,准确地说是:

listBox1.Resources[SystemColors.InactiveSelectionHighlightBrushKey] = new SolidColorBrush(Color.FromArgb(255, (byte)51, (byte)153, (byte)255));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM