String array as comma delimited string in XAML

How can I set the value of the string [] property in xaml?

I control hava with the following property: string [] PropName

I want to set the value of this property as follows:

<ns:SomeControl PropName="Val1,Val2" /> 
+6
source share
4 answers

You can use the <x:Array> markup extension , but its syntax is pretty verbose.

Another option is to create your own TypeConverter , which can convert from a comma-separated list to an array:

 class ArrayTypeConverter : TypeConverter { public override object ConvertFrom( ITypeDescriptorContext context, CultureInfo culture, object value) { string list = value as string; if (list != null) return list.Split(','); return base.ConvertFrom(context, culture, value); } public override bool CanConvertFrom( ITypeDescriptorContext context, Type sourceType) { if (sourceType == typeof(string)) return true; return base.CanConvertFrom(context, sourceType); } } 

If the type you converted was your type, you can apply the [TypeConverter] attribute to that type. But since you want to convert to string[] , you cannot do this. Therefore, you must apply this attribute to all properties where you want to use this converter:

 [TypeConverter(typeof(ArrayTypeConverter))] public string[] PropName { get; set; } 
+7
source
  <ns:SomeControl> <SomeControl.PropName> <x:Array Type="sys:String"> <sys:String>Val1</sys:String> <sys:String>Val2</sys:String> </x:Array> </SomeControl.PropName> </ns:SomeControl> 
+3
source

The idea is to define custom values ​​as Array in the resources of the control / window, and then just use the binding to a static resource:

 <!-- or Window.Resources --> <UserControl.Resources> <x:Array x:Key="CustomValues" Type="sys:String" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:sys="clr-namespace:System;assembly=mscorlib"> <sys:String>Val1</sys:String> <sys:String>Val2</sys:String> </x:Array> </UserControl.Resources> <!-- Then just bind --> <ns:SomeControl PropName="{Binding Source={StaticResource CustomValues}}" /> 
+2
source

sll's answer is fine, but you can avoid the resource if you want and write the value directly to the control:

 <ns:SomeControl> <ns:SomeControl.PropName> <x:Array Type="sys:String" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:sys="clr-namespace:System;assembly=mscorlib"> <sys:String>Val1</sys:String> <sys:String>Val2</sys:String> </x:Array> </ns:SomeControl.PropName> </ns:SomeControl> 

In addition, you can move xmlns: declarations to the head element (Window, UserControl, etc.) so that you do not clutter up your control properties.

PS: If you are developing SomeControl , I would use the svick approach and provide TypeConverter.

+2
source

Source: https://habr.com/ru/post/903279/


All Articles