C# wpf style中实现ListBox自动生成序号


前言

本文是《C# wpf 一种style中调用cs代码的方法》的示例,也是《C# wpf ListBox自动生成序号》的另一种实现。在style中生成序号,ListBox中的元素的文本标签只需应用style即可。


提示:以下是本篇文章正文内容,下面案例可供参考

一、实现步骤

1.创建资源字典

创建一个资源字典用于定义style。名称为TextBlockStyle.xaml。
在这里插入图片描述
创建之后如下图所示。
在这里插入图片描述

2.创建cs文件

创建一个资源字典对应的cs文件,这里要注意名称要与资源字典文件名相同加cs后缀,这样vs会把cs文件当成资源字典文件的附属文件,可以自动折叠。如下图所示。
在这里插入图片描述

cs文件就会变成资源字典的附属文件。
在这里插入图片描述

2.定义附加属性

在TextBlockStyle.xaml.cs中定义一个附加属性,名称为TextBlockInit。附加属性通过propa+tab的方式快捷定义。

using System.Windows;
namespace WpfApp1
{
    class TextBlockStyle
    {
        public static bool GetTextBlockInit(DependencyObject obj)
        {
            return (bool)obj.GetValue(TextBlockInitProperty);
        }
        public static void SetTextBlockInit(DependencyObject obj, bool value)
        {
            obj.SetValue(TextBlockInitProperty, value);
        }
        // Using a DependencyProperty as the backing store for TextBlockInit.  This enables animation, styling, binding, etc...
        public static readonly DependencyProperty TextBlockInitProperty =
            DependencyProperty.RegisterAttached("TextBlockInit", typeof(bool), typeof(TextBlockStyle), new PropertyMetadata(false,PropertyChangedCallback));
    }
}

3.附加属性赋值

在资源字典中,定义一个Style标签,名称为TextBlockStyle_Generate_Sequence_Number,并给上述定义的附加属性赋值。

<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
                    xmlns:local="clr-namespace:WpfApp1">
    <Style x:Key="TextBlockStyle_Sequence_Number" TargetType="TextBlock">
    <!--给附加属性赋值-->
    <Setter Property="local:TextBlockStyle.TextBlockInit" Value="True"></Setter>
</Style>
</ResourceDictionary>

4.回调中实现逻辑

在TextBlockStyle.xaml.cs的TextBlockInit依赖属性改变回调事件中注册TextBlock的Loaded事件,然后根据《C# wpf ListBox自动生成序号》的方法,实现序号功能。

static T GetAncestor<T>(Visual v) where T : DependencyObject
{
    var a = VisualTreeHelper.GetParent(v);
    while (a != null)
    {
        if (a is T)
            return (T)a;
        a = VisualTreeHelper.GetParent(a);
    }
    return null;
}
static void PropertyChangedCallback(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
    //d即是Style应用的对象。
    var textBlock = d as TextBlock;
    //注册Loaded事件
    textBlock.Loaded += (S, E) =>
    {
        TextBlock tb = S as TextBlock;
        var lb = GetAncestor<Selector>(tb);
        if (lb == null)
            return;
        tb.Text = (lb.Items.IndexOf(tb.DataContext) + 1).ToString();
    };
}

二、使用方法

引用资源字典

<ResourceDictionary>
    <ResourceDictionary.MergedDictionaries>
        <ResourceDictionary Source="TextBlockStyle.xaml" />
    </ResourceDictionary.MergedDictionaries>
</ResourceDictionary>

在ListBox中的TexBlock使用Style

<ListBox  Height="552"   Width="440" >
    <ListBox.ItemTemplate>
        <DataTemplate>
            <StackPanel Orientation="Horizontal" Width="200">
                <!--使用style自动生成序号-->
                <TextBlock Style="{DynamicResource TextBlockStyle_Sequence_Number}"  VerticalAlignment="Center"  FontSize="32"   Foreground="#999999" ></TextBlock>
                <TextBlock Margin="20" HorizontalAlignment="Center" VerticalAlignment="Center" FontSize="32"   Foreground="#666666"  Text="张三"></TextBlock>
            </StackPanel>
        </DataTemplate>
    </ListBox.ItemTemplate>
    <ListBox.Items>
        <Control/>
        <Control/>
        <Control/>
        <Control/>
        <Control/>
        <Control/>
    </ListBox.Items>
</ListBox>

显示效果
在这里插入图片描述
注:支持ItemsSource绑定的方式,上面示例是为了方便编写使用了<ListBox.Items>。


完整代码

https://download.csdn.net/download/u013113678/34702454
注:本文已经包含了完整代码的所有片段,只需要自己拼凑即可。上述链接是包含完整代码的vs2019项目可直接运行。


总结

以上就是今天要讲的内容,本文介绍的在style中实现的自动生成序号功能,相对于《C# wpf ListBox自动生成序号》减少了代码耦合和冗余,不需要在每个地方都注册TextBlock的Loaded事件,只需要引用资源字典使用style。而且定义在资源字典中还具有通用性,放到任何项目都可以直接使用。

  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

CodeOfCC

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值