我猜你可能正在寻找这样的东西。
如果你有一个绑定到你的 ListBox 的模型类,这很容易实现。
请按照以下步骤操作
第 1 步 - 创建一个模型类,假设为“ListBoxItemModel.cs”
public class ListBoxItemModel
{
public string Text { get; set; }
public Brush ForegroundBrush { get; set; }
}
注意:-我在这里没有遵循任何 MVVM 方法进行演示。如果您熟悉,则可以使用此代码实现。
第 2 步 - 使用 ListBox 创建一个窗口,并在 MainWindow 中为您的 Model 类定义一个 DataTemplate,如下所示。
将 DataTemplate 分配给 ListBox ItemTemplate 属性。
<Window x:Class="SO61263305.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:SO61263305"
mc:Ignorable="d"
Title="MainWindow" Height="450" Width="800">
<Window.Resources>
<DataTemplate x:Key="LocalTemplate" DataType="local:ListBoxItemModel">
<TextBlock Text="{Binding Text}" Foreground="{Binding ForegroundBrush}" />
</DataTemplate>
</Window.Resources>
<Grid>
<Grid.RowDefinitions>
<RowDefinition />
<RowDefinition />
</Grid.RowDefinitions>
<ListBox x:Name="ItemsListBox" Grid.Row="0" Height="200" Width="200"
ItemTemplate="{StaticResource LocalTemplate}"/>
</Grid>
第 3 步 - 创建一个“ListBoxItemModel”列表,并从您的窗口或用户控件的代码隐藏中绑定到 ListBox。就我而言,它是 MainWindow.xaml.cs
private void LoadDataObjects()
{
var items = new List<ListBoxItemModel>();
var item = new ListBoxItemModel()
{
Text = "John ABCD 1",
ForegroundBrush = new SolidColorBrush(Color.FromRgb(0, 0, 0))
};
items.Add(item);
item = new ListBoxItemModel()
{
Text = "John ABCD 2",
ForegroundBrush = new SolidColorBrush(Color.FromRgb(200, 79, 24))
};
items.Add(item);
ItemsListBox.ItemsSource = items;
}
在上述方法中,您需要为每个项目添加要显示的文本和前景画笔。
第 4 步 - 从代码隐藏的构造函数中调用上述方法,或者您可以从任何其他事件(如按钮单击)中调用以将数据加载到列表框。
请看下面我完整的 MainWindow.xaml.cs(MainWindow 后面的代码)
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
LoadDataObjects();
}
private void LoadDataObjects()
{
var items = new List<ListBoxItemModel>();
var item = new ListBoxItemModel()
{
Text = "John ABCD 1",
ForegroundBrush = new SolidColorBrush(Color.FromRgb(0, 0, 0))
};
items.Add(item);
item = new ListBoxItemModel()
{
Text = "John ABCD 2",
ForegroundBrush = new SolidColorBrush(Color.FromRgb(200, 79, 24))
};
items.Add(item);
ItemsListBox.ItemsSource = items;
}
}
希望这能给您一些想法,您可以在此基础上改进您的要求。
尝试一下,如果您遇到任何困难,请告诉我们。