c# - 始终使用 Run Tag 的 TextBlock 样式

标签 c# wpf arabic right-to-left

在 WPF 阿拉伯语模式下 (FlowDirection="RightToLeft")。

当我给出一个像 -24.7% 这样的数字时,它将打印为 %24.7-

以下代码将解决上述问题。

<Window.Resources>

    <Style TargetType="Run">
        <Setter Property="FlowDirection" Value="LeftToRight" />
    </Style>      

</Window.Resources>

<Grid FlowDirection="RightToLeft" >
    <Grid HorizontalAlignment="Left" Margin="114,127,0,0"  VerticalAlignment="Top" Width="279" Height="97">
        <TextBlock x:Name="textBlock" Text="-24.7%" ><Run></Run></TextBlock>
    </Grid>
</Grid>

现在我想把 <run><run>标记到我所有的文本 block 内容,我怎样才能实现这一点,所以我不必替换代码中的所有文本 block 。

如何通过创建样式来做到这一点...??

注意:我无法使用 TextAlign=Right 解决方案,因为我无法编辑应用程序中的所有文本 block

最佳答案

不能说我喜欢你的方法,但我不知道阿拉伯语陷阱和你的情况,所以不会争论这个。您可以使用附加属性(或混合行为)实现您想要的。像这样:

public static class StrangeAttachedProperty {
    public static bool GetAddRunByDefault(DependencyObject obj) {
        return (bool) obj.GetValue(AddRunByDefaultProperty);
    }

    public static void SetAddRunByDefault(DependencyObject obj, bool value) {
        obj.SetValue(AddRunByDefaultProperty, value);
    }

    public static readonly DependencyProperty AddRunByDefaultProperty =
        DependencyProperty.RegisterAttached("AddRunByDefault", typeof (bool), typeof (StrangeAttachedProperty), new PropertyMetadata(AddRunByDefaultChanged));

    private static void AddRunByDefaultChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) {
        var element = d as TextBlock;
        if (element != null) {
            // here is the main point - you can do whatever with your textblock here
            // for example you can check some conditions and not add runs in some cases
            element.Inlines.Add(new Run());
        }
    }
}

并在您的资源中为所有文本 block 设置此属性:

<Window.Resources>
    <Style TargetType="TextBlock">
        <Setter Property="local:StrangeAttachedProperty.AddRunByDefault" Value="True" />
    </Style>
    <Style TargetType="Run">
        <Setter Property="FlowDirection" Value="LeftToRight" />
    </Style>
</Window.Resources>

关于c# - 始终使用 Run Tag 的 TextBlock 样式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36265185/

相关文章:

c# - 是否可以动态地将事件添加到 XAML 中的按钮?

c# - 如何将图像大小限制为其父容器

ios - Swift - 根据阿拉伯组合字符拆分文本

sql - 如何在 SQLite 中使用阿拉伯逗号选择 SQL

c# - 如何让 JObject.FromObject(object) 包含类型信息?

c# 只显示 DateTime 的时间部分

wpf - 在处理时更新 WPF UI - 异步等待的最佳使用

c# - 使用 OAuth 在 C# 中使用 Twitter API 在 Twitter 中发布阿拉伯字符

c# - 如何使用 Blazor 在客户端生成和保存文件?

WPF 键手势 PageDown 在菜单项中显示为“Next”