I'm trying to bind a DataTable
to a ListView. Since the number of columns is unknown, the binding is done programmatically. There are basically two ways of binding: DisplayMemberBinding
and templates. How can I either style DisplayMemberBinding
or bind a template to a cell?
Here is my code:
private void FillListView(DataTable table)
{
GridView grid = (GridView)lvMain.View;
DataTemplate template = (DataTemplate)FindResource("cellTemplate");
foreach (DataColumn col in table.Columns)
{
var gridColumn = new GridViewColumn()
{
Header = col.ColumnName,
// One of these works, displaymember has higher priority
DisplayMemberBinding = new Binding(col.ColumnName),
CellTemplate = template
};
grid.Columns.Add(gridColumn);
}
lvMain.ItemsSource = ((IListSource)table).GetList();
}
And XAML code:
<UserControl.Resources>
<DataTemplate x:Key="cellTemplate" x:Name="cellTemplate">
<DataTemplate.Resources>
<Style TargetType="Border">
<Style.Triggers>
<Trigger Property="IsMouseOver" Value="True">
<Setter Property="Background" Value="Black"/>
</Trigger>
<Trigger Property="IsMouseOver" Value="False">
<Setter Property="Background" Value="White"/>
</Trigger>
</Style.Triggers>
</Style>
</DataTemplate.Resources>
<Border >
<StackPanel>
<!-- How can I bind here? -->
<TextBlock Text="{Binding}"/>
</StackPanel>
</Border>
</DataTemplate>
</UserControl.Resources>
<ListView x:Name="lvMain">
<ListView.View>
<GridView>
</GridView>
</ListView.View>
</ListView>
You need to create a DataTemplate
per property to bind to.
You may create the them programmatically using the XamlReader.Parse
method:
private static DataTemplate CreateTemplate(string sourceProperty)
{
string Xaml = "<DataTemplate xmlns=\"http://schemas.microsoft.com/winfx/2006/xaml/presentation\">" +
" <DataTemplate.Resources>" +
" <Style TargetType=\"Border\">" +
" <Style.Triggers>" +
" <Trigger Property=\"IsMouseOver\" Value=\"True\">" +
" <Setter Property=\"Background\" Value=\"Black\"/>" +
" </Trigger>" +
" <Trigger Property=\"IsMouseOver\" Value=\"False\">" +
" <Setter Property=\"Background\" Value=\"White\"/>" +
" </Trigger>" +
" </Style.Triggers>" +
" </Style>" +
" </DataTemplate.Resources>" +
" <Border>" +
" <StackPanel>" +
" <TextBlock Text=\"{Binding " + sourceProperty + "}\"/>" +
" </StackPanel>" +
" </Border>" +
" </DataTemplate>";
return XamlReader.Parse(Xaml) as DataTemplate;
}
var gridColumn = new GridViewColumn()
{
Header = col.ColumnName,
CellTemplate = CreateTemplate(col.ColumnName)
};
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.