0

私は listBox を持っています。これは明らかにデータ バインディングによってリスト アイテムでいっぱいになります。また、おそらくご存じのとおり、次のように listItem テンプレート タグを使用して listItem がどのように見えるかを指定します。

<ListBox.ItemTemplate>
    <TextBlock Name="lblName" Text="{Binding Name}" Foreground="black" />
</ListBox.ItemTemplate>

listItems Textbloxk の Foreground が黒であることに注意してください...

今私のC#コードでは、各listItems Textblock Foregroundを必要な色に動的に設定したいと思います。特定の listItems Textblock を参照し、その Foreground を設定するにはどうすればよいですか?

さらに情報が必要な場合は、お問い合わせください。前もって感謝します!

4

2 に答える 2

2

コードビハインドで本当にそれを行う必要がありますか?

推奨される解決策はForeground、ViewModel の ForegroundColor プロパティにプロパティをバインドすることです (MVVM を使用する場合)。

MVVM を使用せず、モデル クラスをプロパティで「汚染」したくない場合は、クラスに既にあるプロパティ (または など)にプロパティをBrushバインドし、 a を使用して aにすることができます。ForegroundNameAgeConverterBrush

<ListBox.ItemTemplate>
    <TextBlock Name="lblName" Text="{Binding Name}" Foreground="{Binding Age, Converter={StaticResource AgeToColorConverter}}" />
</ListBox.ItemTemplate>

そして、コンバーターのコード:

public class AgeToColorConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        // Your code that converts the value to a Brush
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        throw new NotImplementedException();
    }
}
于 2013-01-11T08:23:48.497 に答える
1

より適切で簡単な解決策は、色を表す SolidColorBrush タイプのアイテムにプロパティを追加し、id ForegroundColor を呼び出してバインディングを使用することです。

<ListBox.ItemTemplate>
    <TextBlock Name="lblName" Text="{Binding Name}" Foreground="{Binding ForegroundColor}" />
</ListBox.ItemTemplate>
于 2013-01-11T08:15:12.387 に答える