c# - 绑定(bind)到数组支持的属性

标签 c# wpf xaml

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

    #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

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

最佳答案

在 XAML 中使用字符串[]

您可以在 XAML 中实例化您的关键字属性,如下所示:

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

注意:这假定命名空间声明

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

您可以将 ItemsControl 绑定(bind)到您的关键字,如下所示:

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

在此示例中,每个关键字将显示为单独的列表框项目。

在 WPF 中为此目的使用 string[] 是完全符合规范的,只要保证数组成员永远不会更改(您可以用新数组替换数组,但不能更改其元素)。这是因为数组没有更改通知机制。

如果您的元素可能会改变

如果您的关键字数组的元素可能会改变,您应该使用 ObservableCollection 而不是数组。使它成为一个只读的 CLR 属性(不是依赖属性)并在你的构造函数中初始化它。然后您可以完全按照上面所示在 XAML 中填充它,但对集合的任何更改都会立即反射(reflect)在您的 UI 中。

我实际上为此使用了我自己的集合类,它比 ObservableCollection 具有更多的功能。使用什么集合类并不重要,只要它实现了 INotifyCollectionChanged。

使用纯 XAML 使列表可更新

您不能使用绑定(bind)更新关键字数组。如果您需要更新关键字并希望完全使用 XAML 和绑定(bind)来完成,您需要创建一个包含字符串的关键字对象类,然后将它们放入 ObservableCollection 或类似对象中。

IValueConverter

另一种方法是使用 IValueConverter 将逗号分隔的字符串列表与 string[] 相互转换,如下所示:

<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(',');
  }
}

关于c# - 绑定(bind)到数组支持的属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4148312/

相关文章:

c# - 在 XAML 中绑定(bind)其 SelectedItem 和 ItemsSource 时设置 ComboBox 的 SelectionChanged 事件

wpf - 在 MyUserControl.xaml 中以声明方式设置 MyUserControl 的属性

c# - 如何为 WPF 页面赋予标题

c# - 将按钮 XAML 更改为 C#

c# - MVC 4 : View is not rendered with the correct data from a List<> in the Model

c# - 数据绑定(bind)主窗口的标题以查看模型的属性

c# - 将选项卡控件的 SelectedItem 与 MVVM 绑定(bind)是个好主意吗?

c# - Win32 API LogonUser 离线访问本地账户

c# - C# 应用程序中的资源和嵌入式资源有什么区别?

c# - CA1305 : Verbosity when specifying culture