【发布时间】:2012-02-18 18:34:16
【问题描述】:
我有一个自定义的 ContentControl
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;
【问题讨论】:
-
我有,但不能解决问题。 .Net 4.0 解决方案不保留 ItemsSource 绑定,更糟糕的是会丢失 ListBox.ItemTemplate 中标签上的内容绑定。创建 ExpressionConverter 修复了 Content 绑定,但仍不保存 ItemsSource 绑定。