我想根据用户输入填充列表框。用户输入是一个字符串数组,我在其中检查每个字符串。我处理字符串(例如更正任何拼写错误)并将字符串作为项目放在列表框中。我想为项目着色以指示我是否理解输入。我有4个条件,所以有4种颜色。
我设法在列表框中获得所需的文本,但到目前为止我没有找到解决方法如何进行着色。
这是xaml的一部分:
<Window x:Class="QuickSlide_2._0.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:c="clr-namespace:QuickSlide_2._0"
Title="MainWindow" Height="350" Width="525" WindowStyle="None" ShowInTaskbar="True" AllowsTransparency="True" Background="DarkGray" WindowStartupLocation="CenterScreen" MinHeight="720" MinWidth="1280" Loaded="Window_Loaded">
<Grid VerticalAlignment="Center">
<Grid.Resources>
<c:coll_items x:Key="item"/>
</Grid.Resources>
--------
<ListBox Height="468" HorizontalAlignment="Left" Margin="789,144,0,0" Name="output" VerticalAlignment="Top" Width="450" ItemsSource="{StaticResource item}">
<ListBox.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding Path=item_text}" Background="{Binding Path=background_color}" Width="440" />
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
----------
</Grid>
</Window>
这是构建列表框的c#代码的一部分:
public class item
{
public string item_text {get; set;}
public SolidColorBrush background_color {get; set;}
public item(String item_text, SolidColorBrush background_color)
{
this.item_text = item_text;
this.background_color = background_color;
}
}
public partial class MainWindow : Window
{
public ObservableCollection<item> coll_items;
private void Check_input_Click(object sender, RoutedEventArgs e)
{
private string[] split_input;
private string[,] Results;
// Split the input from richtextbox into a string[] array
TextRange textrange = new TextRange(input_dump.Document.ContentStart, input_dump.Document.ContentEnd);
split_input = textrange.Text.Split(new[] { "\n" }, StringSplitOptions.RemoveEmptyEntries);
// Validate the input
Results = InputEngine.check_input(split_input);
// The first column in results holds the string, the second holds the status
// Add the results to the listbox
for (int i = 0; i < Results.Length / 7; i++)
{
if ( Results[i,1] == 1)
{
coll_items.Add(new item(Results[i,0],new SolidColorBrush(Colors.Green)));
}
else if ( Results[i,1] == 2)
{
coll_items.Add(new item(Results[i,0],new SolidColorBrush(Colors.Yellow)));
}
else if ( Results[i,1] == 3)
{
coll_items.Add(new item(Results[i,0],new SolidColorBrush(Colors.Red)));
}
else
{
coll_items.Add(new item(Results[i,0],new SolidColorBrush(Colors.Blue)));
}
}
this.DataContext = this;
----------
}
我有几年(夜间)编程经验,但WPF很新。我可能犯了一个非常明显的错误,但请帮助我找到它。