我正在尋找更改串列視圖中前 3 個標簽的前景色的方法。我的作業代碼取決于使用 ObservableCollection 的值,但正在尋找僅更改前 3 個標簽的顏色的方法。

我的 ProductItem(主題)中的代碼
<Label Content="{Binding Tonnes}"
FontWeight="Bold"
HorizontalAlignment="Center"
Padding="0,0,0,0"
FontSize="16"
Foreground="{Binding Tonnes, Converter={StaticResource ColorConverter}}"/>
色彩轉換
public class ColorConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
decimal tempValue = decimal.Parse(value.ToString());
string tempString = "Red";
if (tempValue >= 0 && tempValue <= 1)
tempString = "Red";
if (tempValue > 1 && tempValue <= 2)
tempString = "#EDDF00";
if (tempValue > 2 && tempValue <= 5)
tempString = "Green";
SolidColorBrush brush = new SolidColorBrush();
BrushConverter conv = new BrushConverter();
brush = conv.ConvertFromString(tempString) as SolidColorBrush;
return brush;
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
throw new NotImplementedException();
}
}
uj5u.com熱心網友回復:
您可以使用承載標簽的 ListViewItem 的索引號。假設您要將前 3 項的 Foreground 更改為橙色,修改 MultiBinding 的轉換器。
public class ColorConverter : IMultiValueConverter
{
public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
{
if ((values is { Length: 2 }) &&
(values[0] is decimal tempValue) &&
(values[1] is ListViewItem listViewItem))
{
ListView listView = (ListView)ItemsControl.ItemsControlFromItemContainer(listViewItem);
int index = listView.ItemContainerGenerator.IndexFromContainer(listViewItem);
if (index <= 2)
return Brushes.Orange; // Brush for top 3 items
// Do the conversion for other items.
}
return DependencyProperty.UnsetValue;
}
public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture)
{
throw new NotSupportedException();
}
}
然后修改 Foreground 屬性的系結。
<Label Content="{Binding Tonnes}">
<Label.Foreground>
<MultiBinding Converter="{StaticResource ColorConverter}">
<Binding Path="Tonnes"/>
<Binding RelativeSource="{RelativeSource AncestorType={x:Type ListViewItem}}"/>
</MultiBinding>
</Label.Foreground>
</Label>
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/449082.html
下一篇:Tabview滾動行為
