在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>();
}
}
答案 0 :(得分:1)
我希望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>