我有一个自定义的 ContentControl。
以下样式应用了模板:
如果我使用XamlWriter保存这个样式,然后再次读取它,ItemsSource绑定就会丢失,但Label上的Content绑定不会丢失。
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绑定就会丢失,但Label上的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;