c# - 在 WPF ListView c# 窗口中更改外观行

标签 c# wpf data-binding

在我的 Windows 应用程序中,我定义了一个带有列表的窗口。此列表中有基于 Binder 的项目(目前我以编程方式放入项目)。

<ListView x:Name="event_list" IsEnabled="False">
    <ListView.View>
        <GridView>
            <GridViewColumn Header="Type" DisplayMemberBinding="{Binding Path=Type}"/>
            <GridViewColumn Header="Description" DisplayMemberBinding="{Binding Path=Description}"/>
        </GridView>
    </ListView.View>
</ListView>

var row = new { Type = "type", Description = "description" };
event_list.Items.Add(row);

假设我想更改第 3 行并使字体粗细,我该如何实现?

很明显,以下代码无法编译:

event_lits.Items[2].FontWeight = FontWeights.Bold;

因为 Items 属性只返回我输入的字符串,而不是行本身的 View 对象。

热心回答者注意事项: 在 wpf 窗口中,ListView 是 this类,而不是 this类(9/10 谷歌搜索此主题失败的原因)。

最佳答案

您可以添加一个 ItemContainerStyle 和一个绑定(bind)到数据对象属性的 DataTrigger:

<ListView x:Name="event_list" IsEnabled="False">
    <ListView.ItemContainerStyle>
        <Style TargetType="ListViewItem">
            <Style.Triggers>
                <DataTrigger Binding="{Binding IsBold}" Value="True">
                    <Setter Property="FontWeight" Value="Bold" />
                </DataTrigger>
            </Style.Triggers>
        </Style>
    </ListView.ItemContainerStyle>
    <ListView.View>
        <GridView>
            <GridViewColumn Header="Type" DisplayMemberBinding="{Binding Path=Type}"/>
            <GridViewColumn Header="Description" DisplayMemberBinding="{Binding Path=Description}"/>
        </GridView>
    </ListView.View>
</ListView>

示例数据:

event_list.Items.Add(new { Type = "type", Description = "description" });
event_list.Items.Add(new { Type = "type", Description = "description" });
event_list.Items.Add(new { Type = "type", Description = "description", IsBold = true });
event_list.Items.Add(new { Type = "type", Description = "description" });

在 WPF 中,您通常不应该在代码隐藏中设置可视容器的属性。

关于c# - 在 WPF ListView c# 窗口中更改外观行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48889132/

相关文章:

c# - 我如何在 C# 中表示像 1/3 这样的分数?

c# - 忽略 TcpClient/NetworkStream 中的传入数据

javascript - 如果所有值都为 true,Knockout JS 单选按钮会选择最后一个按钮

c# - 推送通知 : Navigate to a ViewController from the AppDelegate

c# - 更新数据库上下文以包含 View 模型

c# - 数组或 IEnumerable 的 DataTemplate

c# - 追踪 WPF 中的内存泄漏

C# WPF 应用程序 .NET Framework 4.8 与 .NET Core 3.1 与 .NET 5.0

data-binding - 组件输入属性上的双向数据绑定(bind)

c# - 在我的 C# XAML Windows 8.1 应用程序中,如何进行编程绑定(bind)?