c# - 绑定(bind)运行次数可变的 RichTextBox

标签 c# wpf xaml richtextbox

我最近在做一个项目,我觉得一个不错的解决方案是在 RichTextBox 中显示一个段落,该段落绑定(bind)到一组对象,这些对象将包含一个字符串和一些关于那个字符串。我希望我能做这样的事情:

<RichTextBox Name="rtb" IsReadOnly="True" FontSize="14" FontFamily="Courier New">
    <FlowDocument>
        <Paragraph>
            <Run Foreground="Red" Text="{Binding foo}"/>
            <Run Foreground="Green" Text="{Binding bar}"/>
            <Run Foreground="Blue" Text="{Binding baz}"/>
        </Paragraph>
    </FlowDocument>
</RichTextBox>

这很好用,但是这是提前定义了所有绑定(bind),但实际上我直到运行时才知道它们,每个字符串都将存储到一个集合中。我正在想办法定义和绑定(bind)多个Run block ,并将它们全部放在要显示的RichTextBox 中。如果可能的话,我更喜欢主要是 xaml 的解决方案,但如果我必须在后面的代码中这样做,那可能没问题,只要绑定(bind)坚持并且所有内容在初始加载后正确更新即可。

我尝试过类似的方法,但无法弄清楚如何从后面的代码绑定(bind)到 RunText 属性:

foreach (var item in col)
{        
    Run run = new Run();
    Binding b = new Binding();
    b.Source = this;
    b.Path = new PropertyPath(item.StaticText);
    run.SetBinding(run.Text, b);    //Tells me Text is not a dependency property
                                    //But it could be bound if this were xaml?
}

我还尝试将 ItemsControl 放入 RichTextBox 中,将 Run 作为项目的数据模板,但它不允许我将数据模板设为 Run 标记,但我不确定它是否能正常工作。

关于最佳方法的任何指导,或者我的解决方案有什么问题。

最佳答案

你可以用这个...

<Paragraph>
    <ItemsControl ItemsSource="{Binding MyRuns}">
        <ItemsControl.ItemTemplate>
            <DataTemplate>
                <TextBlock>
                    <Run Foreground="{Binding Color}" Text="{Binding Text}"/>
                </TextBlock>
            </DataTemplate>
        </ItemsControl.ItemTemplate>
        <ItemsControl.ItemsPanel>
            <ItemsPanelTemplate >
                <StackPanel Orientation="Vertical" />
            </ItemsPanelTemplate>
        </ItemsControl.ItemsPanel>
    </ItemsControl>
    <!--<Run Foreground="Red" Text="{Binding foo}"/>
    <Run Foreground="Green" Text="{Binding bar}"/>
    <Run Foreground="Blue" Text="{Binding baz}"/>-->
</Paragraph>

并将 MyRuns 定义为 View 模型中的集合,例如

public ObservableCollection<RunData> MyRuns { get; set; }  

将属性放入您的 RunData 等中。

你当然可以删除 ItemsControl.ItemsPanel,那只是为了好玩

关于c# - 绑定(bind)运行次数可变的 RichTextBox,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15947880/

相关文章:

c# - 如何在 LINQ 的表达式树中创建连接?

wpf - 使用 MVVM 根据 WPF 中的复选框选择启用/禁用文本框

c# - 使用 Caliburn.Micro 附加到多个事件

c# - 使用绑定(bind)更改 GridView 项的可见性

c# - 在应用程序之间发送套接字 c#

c# - Entity Framework 包含左连接这可能吗?

c# - 什么相当于 C# 中的 Windows API CreateEvent 函数

c# - 在 XAML 中使用 System.Type

c# - 对十进制类型的列进行排序? WPF DataGrid 中的(可为空)

wpf - 在 XAML 中绑定(bind)到窗口事件