gpt4 book ai didi

c# - WPF ListView GridView 单元格样式和绑定(bind)

转载 作者:行者123 更新时间:2023-12-04 10:26:33 27 4
gpt4 key购买 nike

我正在尝试绑定(bind) DataTable到一个 ListView 。由于列数未知,绑定(bind)以编程方式完成。绑定(bind)方式基本有两种:DisplayMemberBinding和模板。我怎样才能样式DisplayMemberBinding或将模板绑定(bind)到单元格?

这是我的代码:

    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();
}

和 XAML 代码:
<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>

最佳答案

您需要创建一个 DataTemplate每个要绑定(bind)的属性。

您可以使用 XamlReader.Parse 以编程方式创建它们。方法:

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)
};

关于c# - WPF ListView GridView 单元格样式和绑定(bind),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60619411/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com