用于收据预览的 WPF 自定义控件 [英] WPF Custom control for receipt preview

查看:33
本文介绍了用于收据预览的 WPF 自定义控件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要在 WPF 页面中显示收据预览.附上收据样本.

I have a requirement to show receipt preview as part of WPF page. Sample of receipt is attached.

收据上的每一行文本都可以有不同的对齐方式(有些居中、有些居右或居左)和颜色,具体取决于配置.此外,每种收据类型的行数可能有所不同.我想知道要使用哪些控件来有效地实现这一点.我可以根据行数在后面的代码中动态创建标签,并将每个标签与不同的前景色以不​​同的方式对齐,但只是寻找一种有效的方法(如果有的话).收据的宽度不会变化,但长度可能会变化.所有行和所有收据类型的字体都相同.任何想法都非常感谢.

Each line of text on the receipt can have different alignment(some center, some right or left) and color depending on configuration. Also, the number of lines can vary for each receipt type. I am wondering which controls to be used to effectively implement this. I can create labels dynamically in code behind depending on number of lines and align each one differently with different foreground color but just looking for an effective way if there is any. The width of receipt does NOT vary but length may. Font is same for all lines and all receipt types. Any ideas are really appreciated.

谢谢

推荐答案

通常最好避免从代码背后动态添加标签或文本块等控件.这种类型的代码难以阅读,几乎不可能进行测试.相反,您应该使用视图模型类(查找 MVVM 模式).您的视图模型可能有一个返回 ReceiptItem 列表的属性,然后在您的视图(XAML 文件)中创建一个 ItemsControl 并将其绑定到您的 ReceiptItems 列表.现在您可以为 ReceiptItem 类创建一个模板,以便它们使用标签、文本块或任何您认为合适的方式显示所需的内容.

It is normally better to avoid dynamically adding controls like labels or textblocks from your code behind. This type of code is difficult to read and almost impossible to test. Instead, you should use a view-model class (look up the MVVM pattern). Your view-model could have a property returning a list of ReceiptItem and then in your view (the XAML file) you make an ItemsControl and bind it to your list of ReceiptItems. Now you can create a template for the ReceiptItem class so that they show up a desired using Label, TextBlock, or whatever you decide is appropriate.

例如,在 C# 中,您需要两个类:

For example, in C# you would need two classes:

public class MyReceiptViewModel
{
    public List<ReceiptItem> ReceiptItems { get; set; }
}

public class ReceiptItem
{
    public string Content { get; set; }
    public bool IsHighlighted { get; set; }
}

您的视图可能如下所示(假设您有一个 MyReceiptViewModel 实例作为您的数据上下文):

Your view might look like (this assumes that you have an instance of MyReceiptViewModel as your data context):

<ItemsControl ItemsSource="{Binding ReceiptItems}">
    <ItemsControl.ItemTemplate>
        <DataTemplate>
            <TextBlock 
                Text="{Binding Content}" 
                Foreground="{Binding IsHighlighted, Converter={StaticResource MyColorFromBooleanConverter}}" />
        </DataTemplate>
    </ItemsControl.ItemTemplate>
</ItemsControl>

这篇关于用于收据预览的 WPF 自定义控件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆