我知道标准XamlWriter不会保留绑定。但真正太臭的是绑定当前的值并没有被序列化。XamlWriter失去约束力 - 好的!但如何保持价值? (ItemsControl)
我当前 - 真的很蠢 - 解决方法是创建一个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); }
}
}
如果运行这个测试应用程序,将光标移动到不同的文本框,你会看到世界上没有问题的串行化硬编码和直接绑定的值。 相反,数据模板绑定不会被序列化。
的方式存在在使用通过代码来代替一个StaticReference产生的ItemsSource没有区别,只是测试的..
感谢您的回应。看来你是对的..在我的测试床上,我还没有能够重现这个错误。 在我的真实应用程序中有一堆ContentControls。 TabControl,ItemControl,ItemControl。那里的绑定工作通过RelativeSource FindAncestor .. 我会尝试一些更多。看看 – kris 2010-07-13 11:09:25
。 :) – kris 2010-07-13 12:20:37