c# – 如何用StaticResource的字符串填充List
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了c# – 如何用StaticResource的字符串填充List,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2489字,纯文字阅读大概需要4分钟。
内容图文
在我在C#4.0的WPF项目中,在资源字典中我有字符串资源:
<System:String x:Key="s_one">One</System:String>
<System:String x:Key="s_two">Two</System:String>
我想使用上面的字符串来填充xaml文件中的字符串Ls列表.
<cc:XYZ.Ls>
<StaticResource ResourceKey="s_one" />
<StaticResource ResourceKey="s_two" />
</cc:XYZ.Ls>
这不起作用.例外中的细节说明
{“’One’不是属性’Ls’的有效值.”}
但是,当我在这些字符串之前添加另一个字符串时,它运行得很好.
<cc:XYZ.Ls>
<System.String>Zero</System.String>
<StaticResource ResourceKey="s_one" />
<StaticResource ResourceKey="s_two" />
</cc:XYZ.Ls>
运行后Ls中的项目为{“Zero”,“One”,“Two”}
有没有办法将StaticResource中的字符串插入字符串列表而不在XAML中添加额外的字符串?
注意:XYZ类的相关部分:
public partial class XYZ : UserControl
{
public static readonly DependencyProperty LsProperty =
DependencyProperty.Register("Ls", typeof(List<string>), typeof(XYZ),
new FrameworkPropertyMetadata(new List<string>()));
public List<string> Ls
{
get { return (List<string>)GetValue(XYZ.LsProperty); }
set { SetValue(XYZ.LsProperty, value); }
}
public XYZ()
{
InitializeComponent();
Ls = new List<string>();
}
}
解决方法:
我更喜欢this方式
但你可以解决像……
public class ArrayToListConvertor : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
if (value == null)
return new List<string>();
return ((string[]) value).ToList();
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
throw new NotImplementedException();
}
}
public partial class Xyz : UserControl
{
public static readonly DependencyProperty LsProperty =
DependencyProperty.Register("Ls", typeof(List<string>), typeof(Xyz),
new FrameworkPropertyMetadata(null));
public List<string> Ls
{
get { return (List<string>)GetValue(Xyz.LsProperty); }
set { SetValue(Xyz.LsProperty, value); }
}
public Xyz()
{
InitializeComponent();
}
}
<Window.Resources>
<x:Array Type="sys:String" x:Key="lst">
<StaticResource ResourceKey="s_one"/>
<StaticResource ResourceKey="s_two" />
</x:Array>
<wpfApplication2:ArrayToListConvertor x:Key="Conv"></wpfApplication2:ArrayToListConvertor>
</Window.Resources>
<Grid>
<wpfApplication2:Xyz x:Name="Xyz" Ls="{Binding Path=., Source={StaticResource lst}, Converter={StaticResource Conv}}">
</wpfApplication2:Xyz>
<ListBox ItemsSource="{Binding ElementName=Xyz, Path=Ls }">
<ListBox.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding}"></TextBlock>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</Grid>
内容总结
以上是互联网集市为您收集整理的c# – 如何用StaticResource的字符串填充List全部内容,希望文章能够帮你解决c# – 如何用StaticResource的字符串填充List所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。