Binding to properties that support an array

I am trying to create a custom control for the Windows Phone 7 platform. So far I have defined a property and works fine if it is a simple type (like a string), but ultimately it should be an array. Therefore, I define my property as follows:

    #region Keywords

    public string[] Keywords
    {
        get { return (string[])GetValue(KeywordsProperty); }
        set { SetValue(KeywordsProperty, value); }
    }

    public static readonly DependencyProperty KeywordsProperty =
        DependencyProperty.Register(
            "Keywords",
            typeof(string[]),
            typeof(MyType),
            new PropertyMetadata(null));

    #endregion Keywords

Now I want to bind to top support and XAML, but I cannot figure out how to set the property through XAML. Is there a better way to do this?

+3
source share
2 answers

Using string [] in XAML

You can create a keyword property in XAML as follows:

<MyControl ...>
  <MyControl.Keywords>
    <sys:String>Happy</sys:String>
    <sys:String>Sad</sys:String>
    <sys:String>Angry</sys:String>
  </MyControl.Keywords>
</MyControl>

Note. This involves declaring a namespace

xmlns:sys="clr-namespace:System;assembly=mscorlib"

ItemsControl :

<ListBox ItemsSource="{Binding Keywords}" ...>

ListBox.

[] WPF , ( , ). , .

, ObservableCollection . CLR- ( ) . XAML , , .

, , ObservableCollection. , , INotifyCollectionChanged.

XAML

. XAML , Keyword, , ObservableCollection .

IValueConverter

IValueConverter , , [], :

<TextBox Text="{Binding Keywords,
                        Converter={x:Static my:CommaSeparatedConverter.Instance}}" />

:

public class CommaSeparatedConverter : IValueConverter
{
  public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
  {
    return string.Join(",", (string[])value);
  }
  public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
  {
    return ((string)value).Split(',');
  }
}
+5

:

<Textblock Text="{Binding Keywords[0]}" />

, , DataContext.

0

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


All Articles