MVVM绑定到具有ObservableCollection依赖项属性的用户控件

时间:2014-03-13 18:24:11

标签: c# wpf xaml mvvm user-controls

我设计了一个带有ObservableCollection依赖项属性的用户控件,并希望它由MVVM轻量级应用程序使用。如果我在后面的消费视图代码中设置属性,它就像一个魅力,但当我尝试使用视图模型的xaml绑定时,它不是这样。

在控件的代码隐藏中,我定义了依赖属性:

/// <summary>
/// The <see cref="ItemsSource" /> dependency property's name.
/// </summary>
public const string ItemsSourcePropertyName = "ItemsSource";

/// <summary>
/// Gets or sets the value of the <see cref="ItemsSource" />
/// property. This is a dependency property.
/// </summary>
public List<string> ItemsSource
{
    get
    {
        return (List<string>)GetValue(ItemsSourceProperty);
    }
    set
    {
        SetValue(ItemsSourceProperty, value);
    }
}

/// <summary>
/// Identifies the <see cref="ItemsSource" /> dependency property.
/// </summary>
public static readonly DependencyProperty ItemsSourceProperty = DependencyProperty.Register(
    ItemsSourcePropertyName,
    typeof(List<string>),
    typeof(ListEditor), new PropertyMetadata(new List<string>(), OnItemsSourcePropertyChanged));

private static void OnItemsSourcePropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
    ListEditor listEditor = d as ListEditor;
    while (listEditor._stackPanel.Children.Count > 1)
    {
        listEditor._stackPanel.Children.RemoveRange(0, listEditor._stackPanel.Children.Count - 2);
    }

    List<string> newCollection = e.NewValue as List<string>;

    foreach (string item in newCollection)
    {
        ListItemEditor newItem = new ListItemEditor();
        newItem.Text = item;
        newItem.RemoveItem += listEditor.listItemEditor_RemoveItem;

        listEditor._stackPanel.Children.Insert(listEditor._stackPanel.Children.Count - 1, newItem);
    }
} 

在视图中我绑定了控件:

<ucl:ListEditor ItemsSource="{Binding PartNumbers}"/>

在视图模型中,我定义了属性:

/// <summary>
/// The <see cref="PartNumbers" /> property's name.
/// </summary>
public const string PartNumbersPropertyName = "PartNumbers";

private ObservableCollection<string> _partNumbers = new ObservableCollection<string>();

/// <summary>
/// Sets and gets the PartNumbers property.
/// Changes to that property's value raise the PropertyChanged event. 
/// </summary>
public ObservableCollection<string> PartNumbers
{
    get
    {
        return _partNumbers;
    }

    set
    {
        if (_partNumbers == value)
        {
            return;
        }

        RaisePropertyChanging(PartNumbersPropertyName);
        _partNumbers = value;
        RaisePropertyChanged(PartNumbersPropertyName);
    }
}

如何有效促进约束?

0 个答案:

没有答案