嘿。我有一個名爲BackgroundColor的字符串屬性的對象。該字符串是顏色的十六進制表示。我無法改變這個對象。WPF:將一個listviewitem的背景顏色綁定到一個對象的十六進制字符串屬性
我將這些對象的集合綁定到listView。我想要做的是將列表視圖的行的背景綁定到行中顯示的對象的BackgroundColor屬性。
這是什麼最好的方法?
嘿。我有一個名爲BackgroundColor的字符串屬性的對象。該字符串是顏色的十六進制表示。我無法改變這個對象。WPF:將一個listviewitem的背景顏色綁定到一個對象的十六進制字符串屬性
我將這些對象的集合綁定到listView。我想要做的是將列表視圖的行的背景綁定到行中顯示的對象的BackgroundColor屬性。
這是什麼最好的方法?
我認爲使用IValueConverter是合適的解決方案。您可以製作一個將字符串十六進制值轉換爲Color的HexConverter。該鏈接應該讓你開始。
你會想要使用一個樣式綁定ListViewItem的背景到該行的項目。該項目是一個ListViewItem的默認的DataContext所以這應該是簡單的:
<Grid xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:sys="clr-namespace:System;assembly=mscorlib"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<Grid.Resources>
<x:Array x:Key="colors" Type="{x:Type sys:String}">
<sys:String>Red</sys:String>
<sys:String>Yellow</sys:String>
<sys:String>#0000FF</sys:String>
</x:Array>
</Grid.Resources>
<ListView ItemsSource="{StaticResource colors}">
<ListView.Resources>
<Style TargetType="{x:Type ListViewItem}">
<Setter Property="Background" Value="{Binding .}"/>
</Style>
</ListView.Resources>
</ListView>
</Grid>
而是結合整個項目,你會綁定到BACKGROUNDCOLOR,但它應該是類似於以上。你必須使用帶有綁定的轉換器作爲前綴「#」,這是內置BrushConverter將其解析爲十六進制的信號。