gpt4 book ai didi

c# - XamlWriter.Save 丢失了来自 ListBox 的 ItemsSource 绑定(bind)

转载 作者:行者123 更新时间:2023-11-30 17:14:12 26 4
gpt4 key购买 nike

我有一个自定义的 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 绑定(bind)会丢失,但 Label 上的 Content 绑定(bind)不会。

Style style = Application.Current.TryFindResource("DefaultStyle") as Style;

string s = XamlWriter.Save(style);
Style secondStyle = XamlReader.Parse(s) as Style;

有没有办法确保正确序列化 ItemsSource 绑定(bind)或轻松将其添加回去?

尝试从另一个项目的 ResourceDictionary 获取样式时也会发生这种情况,例如

ResourceDictionary styles = new ResourceDictionary();
styles.Source = new Uri(String.Format("pack://application:,,,/StyleCopyTest;component/Styles/{0}Styles.xaml", type));
return styles;

最佳答案

在 WPF 源代码中,ItemsSource 定义为

[Bindable(true), CustomCategory("Content"),     DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public IEnumerable ItemsSource { get; set; }

所以这不能被 XamlWriter 序列化。

因此您必须编写自己的序列化程序或使用提到的方法 here

关于c# - XamlWriter.Save 丢失了来自 ListBox 的 ItemsSource 绑定(bind),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9005029/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com