目前这是我的XAML Listview: 我已经做了很多搜索,但我找不到解决方案,感谢您的帮助。
<ListView x:Name="listView_data" HorizontalAlignment="Center" VerticalAlignment="Bottom" Margin="20,0,20,5" Width="712" Height="357">
<ListView.View>
<GridView x:Name="lvgvc">
<TextBlock.Foreground>
<SolidColorBrush Color="black"></SolidColorBrush>
</TextBlock.Foreground>
</GridView>
</ListView.View>
</ListView>
这是Code-Behind:
//received data in DataTable (dt)
for(int i=0; i < dt.Columns.Count; i++)
{
GridViewColumn gvc = new GridViewColumn();
gvc.Header = "Column"+i;
gvc.Width = 100;
gvc.DisplayMemberBinding = new Binding("column"+i);
lvgvc.Columns.Add(gvc);
}
listView_data.Items.Clear();
listView_data.ItemsSource = dt.DefaultView;
Listview创建列并填充datatTable。但行完全是白色的。我可以在listview中选择6行,因为dataTable中有6行,而调试DataTable则显示其中的正确数据。如何在listview中将文本块颜色设置为黑色。我想根据随机输入栏明智地使用textblock。
答案 0 :(得分:1)
DisplayMemberBinding的路径应设置为列的名称:
for (int i = 0; i < dt.Columns.Count; i++)
{
GridViewColumn gvc = new GridViewColumn();
gvc.Header = "Column" + i;
gvc.Width = 100;
gvc.DisplayMemberBinding = new Binding(dt.Columns[0].ColumnName);
lvgvc.Columns.Add(gvc);
}
listView_data.Items.Clear();
listView_data.ItemsSource = dt.DefaultView;
可以通过在XAML标记中定义ItemContainerStyle来更改列中文本的颜色:
<ListView x:Name="listView_data">
<ListView.View>
<GridView x:Name="lvgvc"/>
</ListView.View>
<ListView.ItemContainerStyle>
<Style TargetType="ListViewItem">
<Setter Property="Foreground" Value="Black" />
</Style>
</ListView.ItemContainerStyle>
</ListView>
如果您想在不同的列中使用不同的颜色,则可以通过编程方式为每列创建DataTemplate:
const string dataTemplate = "<DataTemplate xmlns=\"http://schemas.microsoft.com/winfx/2006/xaml/presentation\"><TextBlock Text=\"{{Binding {0}}}\" Foreground=\"{1}\" /></DataTemplate>";
for (int i = 0; i<dt.Columns.Count; i++)
{
string colour = "Green"; ///change this one based on your colouring logic...
DataTemplate template = System.Windows.Markup.XamlReader.Parse(string.Format(dataTemplate, dt.Columns[0].ColumnName, colour)) as DataTemplate;
GridViewColumn gvc = new GridViewColumn() { CellTemplate = template };
gvc.Header = "Column" + i;
gvc.Width = 100;
lvgvc.Columns.Add(gvc);
}
listView_data.Items.Clear();
listView_data.ItemsSource = dt.DefaultView;