我有一個自ContentControl中XamlWriter.Save失去的ItemsSource從一個ListBox
public class DataControl : ContentControl
{
public List<DataItem> Options
{
get { return (List<DataItem>)GetValue(OptionsProperty); }
set { SetValue(OptionsProperty, value); }
}
public static readonly DependencyProperty OptionsProperty =
DependencyProperty.Register("Options", typeof(List<DataItem>), typeof(DataControl));
public DataControl()
{
Options = new List<DataItem>();
}
public string Label
{
get { return (string)GetValue(LabelProperty); }
set { SetValue(LabelProperty, value); }
}
// Using a DependencyProperty as the backing store for Label. This enables animation, styling, binding, etc...
public static readonly DependencyProperty LabelProperty =
DependencyProperty.Register("Label", typeof(string), typeof(DataControl));
}
public class DataItem
{
public DataItem(string key, string value)
{
Key = key;
Value = value;
}
public string Key { get; set; }
public string Value { get; set; }
}
,其模板由下面的樣式應用結合:
<Style TargetType="{x:Type local:DataControl}" x:Key="DefaultStyle">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type local:DataControl}">
<StackPanel>
<ListBox ItemsSource="{TemplateBinding Options}" >
<ListBox.ItemTemplate>
<DataTemplate>
<Label Content="{Binding Key}" />
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
<Label Content="{TemplateBinding Label}" />
</StackPanel>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
如果我使用的XamlWriter保存這種風格和然後再讀回來,ItemsSource綁定會丟失,但標籤上的Content綁定不是。
Style style = Application.Current.TryFindResource("DefaultStyle") as Style;
string s = XamlWriter.Save(style);
Style secondStyle = XamlReader.Parse(s) as Style;
有沒有一種方法來確保ItemsSource綁定序列化正確或將其輕鬆添加回來?
當嘗試從另一個項目的ResourceDictionary中獲取樣式時,也會發生這種情況,例如,
ResourceDictionary styles = new ResourceDictionary();
styles.Source = new Uri(String.Format("pack://application:,,,/StyleCopyTest;component/Styles/{0}Styles.xaml", type));
return styles;
您是否嘗試過[http://stackoverflow.com/questions/32541/how-can-you-clone-a-wpf-object](http://stackoverflow.com/questions/32541/如何可任意你克隆-A-WPF對象)? –
我有,它不能解決問題。 .Net 4.0解決方案不保留ItemsSource綁定,而更糟糕的是會丟失ListBox.ItemTemplate中Label上的Content綁定。創建ExpressionConverter修復了內容綁定,但仍不保存ItemsSource綁定。 –