我知道标准的 XamlWriter 不会持久绑定。但真正令人讨厌的是绑定持有的当前值也没有被序列化。
我目前 - 真的很愚蠢 - 解决方法是创建一个 DependencyProperty fooProperty 和属性 foo。还有一个属性 foo2。然后 foo 的 Change-eventhandler 将其值写入 foo2。
你看:愚蠢。
有没有人有更好的解决方案?
干杯
-- 编辑回应托马斯 --
基本上你是对的。但是当使用 ItemsControl 时,它看起来有点不同:
<Window x:Class="TestApp.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:TestApp"
Title="MainWindow" Height="350" Width="525"
x:Name="window"
>
<StackPanel>
<StackPanel.Resources>
<x:Array x:Key="arr1" Type="{x:Type local:TestData}">
<local:TestData Message="itemcontrol binding 1"/>
<local:TestData Message="itemcontrol binding 2"/>
</x:Array>
</StackPanel.Resources>
<local:Test Foo="hard coded"/>
<local:Test Foo="{Binding Message, ElementName=window}"/>
<ItemsControl ItemsSource="{StaticResource arr1}">
<ItemsControl.ItemTemplate>
<DataTemplate>
<local:Test Foo="{Binding Path=Message }"/>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
</StackPanel>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
Message = "direct binding";
}
public static DependencyProperty MessageProperty = DependencyProperty.Register("Message", typeof(string), typeof(MainWindow));
public string Message
{
get { return (string)GetValue(MessageProperty); }
set { SetValue(MessageProperty, value); }
}
}
public class Test : TextBox
{
public static DependencyProperty FooProperty = DependencyProperty.Register("Foo", typeof(string), typeof(Test), new PropertyMetadata(OnFooChanged));
private static void OnFooChanged(DependencyObject d, DependencyPropertyChangedEventArgs a)
{
(d as Test).Text = a.NewValue as String;
}
public string Foo
{
get { return (string)GetValue(FooProperty); }
set { SetValue(FooProperty, value); }
}
protected override void OnMouseEnter(MouseEventArgs e)
{
Debug.Print("foo is really: " + Foo);
Debug.Print(XamlWriter.Save(this));
}
}
public class TestData : DependencyObject
{
public static DependencyProperty MessageProperty = DependencyProperty.Register("Message", typeof(string), typeof(TestData));
public string Message
{
get { return (string)GetValue(MessageProperty); }
set { SetValue(MessageProperty, value); }
}
}
如果您运行此测试应用程序并将光标移到不同的文本框上,您会发现序列化硬编码和直接绑定的值没有问题。相反,数据模板化绑定不会被序列化。
顺便说一句,使用代码生成的 ItemsSource 而不是 StaticReference 没有区别,只是测试了一下..