C# 绑定到阵列支持的属性

C# 绑定到阵列支持的属性,c#,wpf,xaml,C#,Wpf,Xaml,我正在尝试为WindowsPhone7平台构建一个自定义控件。到目前为止,我已经定义了这个属性,如果它是一个简单的类型(比如字符串),它就可以正常工作,但这最终需要是一个数组。所以我定义我的属性如下: #region Keywords public string[] Keywords { get { return (string[])GetValue(KeywordsProperty); } set { SetValue(Keywords

我正在尝试为WindowsPhone7平台构建一个自定义控件。到目前为止,我已经定义了这个属性,如果它是一个简单的类型(比如字符串),它就可以正常工作,但这最终需要是一个数组。所以我定义我的属性如下:

    #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
<TextBox Text="{Binding Keywords,
                        Converter={x:Static my:CommaSeparatedConverter.Instance}}" />

现在我想要顶级支持绑定和XAML,但我不知道如何通过XAML设置属性。有更好的方法吗?

在XAML中使用字符串[]

您可以在XAML中实例化Keywords属性,如下所示:

<MyControl ...>
  <MyControl.Keywords>
    <sys:String>Happy</sys:String>
    <sys:String>Sad</sys:String>
    <sys:String>Angry</sys:String>
  </MyControl.Keywords>
</MyControl>
<ListBox ItemsSource="{Binding Keywords}" ...>
您可以将ItemsControl绑定到关键字,如下所示:

<MyControl ...>
  <MyControl.Keywords>
    <sys:String>Happy</sys:String>
    <sys:String>Sad</sys:String>
    <sys:String>Angry</sys:String>
  </MyControl.Keywords>
</MyControl>
<ListBox ItemsSource="{Binding Keywords}" ...>

您应该能够通过以下方式绑定到数组的特定元素:

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


当然,假设关键字在当前DataContext中可用。

我在x:Array上遇到一个错误(找不到类型“x:Array”)。在文档的前面,xmlns:x被定义为“”,而x:x在页面中的其他地方的工作方式与正常情况类似。另外,是否有一种更像WPF的方式来实现这一点?像是一个可观察到的集合之类的。我不会更新列表,只是偶尔检查一下。因为关键字声明为string[],所以在XAML中实际上不需要x:Array语法。我已经把它从我的答案中删除了。(我不明白为什么它对你不起作用:我经常使用x:Array,听起来你做得很对。)我还添加了更多关于何时以及为什么你可以使用ObservableCollection而不是x:Array的信息。该死的家伙,你太棒了。我已经将其转换为只读ObservableCollection,删除了x:array,我在sys:string上有一点错误,但是sys:string可以工作(我不知道为什么)。一切看起来都很好,我真的很高兴能够放下x:B阵列。这样看起来更漂亮、更流线型。我试图将整个字符串数组绑定到一个单独的属性,该属性本身是字符串[],而不是arrayGotcha的一个元素。很抱歉给你带来了困惑。