如何使用具有绑定DependencyProperty的自定义控件序列化RTB的选择?

时间:2014-08-05 17:00:03

标签: c# wpf serialization dependency-properties flowdocument

我有一个样本复制品,尽管有保护,但仍会崩溃。

当我尝试手动序列化包含包含绑定TextRange崩溃的自定义控件的DependencyProperty时,因为它失败了一个断言,因为该属性的值不能分配给属性,因为它是一种表达。

这是我的代码中的错误吗?这是序列化程序中的错误吗?我怎样才能解决这个问题?如何让它在选择中序列化我的自定义类?

我把它缩小到这个:

的Xaml

<Window x:Class="SaveCustomCrash.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:c="clr-namespace:SaveCustomCrash"
    Title="MainWindow" Height="350" Width="525">
  <StackPanel>
    <Button Click="CrashClick">Crash</Button>
    <RichTextBox Name="rtb">
        <FlowDocument>
            <Table>
                <TableRowGroup>
                    <c:CustomRow Settable="{Binding IsVisible,ElementName=rtb}">
                        <TableCell>
                            <Paragraph>Stuff</Paragraph>
                        </TableCell>
                    </c:CustomRow>
                </TableRowGroup>
            </Table>
        </FlowDocument>
    </RichTextBox>
  </StackPanel>
</Window>

代码隐藏:

using System.IO;
using System.Windows;
using System.Windows.Documents;

namespace SaveCustomCrash
{
  public partial class MainWindow
  {
    public MainWindow()
    {
        InitializeComponent();
    }

    private void CrashClick(object sender, RoutedEventArgs e)
    {
        rtb.SelectAll();
        using (var memoryStream = new MemoryStream())
        {
            if (!rtb.Selection.CanSave(DataFormats.Xaml))
            {
                MessageBox.Show("Can't Save"); // this doesn't get hit.
                return;
            }

            try
            {
                rtb.Selection.Save(memoryStream, DataFormats.Xaml, true);
            }
            catch // apparently it can't catch this exception.
            {
            }
            memoryStream.Flush();
            memoryStream.Position = 0;
            using (var streamReader = new StreamReader(memoryStream))
            {
                MessageBox.Show("Xaml: " + streamReader.ReadToEnd());
            }
        }
    }
}

public class CustomRow : TableRow
{
    public static readonly DependencyProperty SettableProperty =
        DependencyProperty.Register("Settable", typeof (bool), typeof (CustomRow), new PropertyMetadata(default(bool)));

    public bool Settable
    {
        get { return (bool) GetValue(SettableProperty); }
        set { SetValue(SettableProperty, value); }
    }
  }
}

1 个答案:

答案 0 :(得分:0)

将所选文本保存到XAML中时,您可以将最后一个参数传递为false,代表 preserveTextElements

rtb.Selection.Save(memoryStream, DataFormats.Xaml, false);