【问题标题】:WPF MVVM Bind list on custom control to ViewModelWPF MVVM 将自定义控件上的列表绑定到 ViewModel
【发布时间】:2010-12-10 11:29:27
【问题描述】:

是否可以将数据绑定到“错误”的方向?我希望将自定义控件中的值绑定到我的 ViewModel。我尝试使用“OneWayToSource”模式绑定,但无法正常工作。

场景(简化):

我有一个自定义控件 (MyCustomControl),它的依赖属性是一个字符串列表:

public class MyCustomControl : Control
{
    static MyCustomControl()
    {
        //Make sure the template in Themes/Generic.xaml is used.
        DefaultStyleKeyProperty.OverrideMetadata(typeof (MyCustomControl),  new FrameworkPropertyMetadata(typeof (MyCustomControl)));

        //Create/Register the dependency properties.
        CheckedItemsProperty = DependencyProperty.Register("MyStringList", typeof (List<string>),  typeof (MyCustomControl), new FrameworkPropertyMetadata(new List<string>()));
    }

    public List<string> MyStringList
    {
        get
        {
            return (List<string>)GetValue(MyCustomControl.MyStringListProperty);
        }
        set
        {
            var oldValue = (List<string>)GetValue(MyCustomControl.MyStringListProperty);
            var newValue = value;
            SetValue(MyCustomControl.MyStringListProperty, newValue);
            OnPropertyChanged(new DependencyPropertyChangedEventArgs(MyCustomControl.MyStringListProperty, oldValue, newValue));
        }
    }
    public static readonly DependencyProperty MyStringListProperty;
}

该控件还包含操作此列表的代码。

我在具有 ViewModel 的 UserControl 中使用此自定义控件。 ViewModel 有一个属性,它也是一个字符串列表:

public List<string> MyStringsInTheViewModel
{
    get
    {
        return _myStringsInTheViewModel;
    }
    set
    {
        if (value != _myStringsInTheViewModel)
        {
            _myStringsInTheViewModel = value;
            OnPropertyChanged("MyStringsInTheViewModel");
        }
    }
}
private List<string> _myStringsInTheViewModel;

现在我想将自定义控件 (MyStringList) 中的列表绑定到 ViewModel (MyStringsInTheViewModel) 中的列表,以便在自定义控件中更改列表时,它也会在 ViewModel 中更改。我已经尝试过了,但无法让它工作......

<myns:MyCustomControl MyStringList="{Binding Path=MyStringsInTheViewModel, Mode=OneWayToSource, UpdateSourceTrigger=PropertyChanged}">

如何进行这样的绑定?

【问题讨论】:

  • 你为什么使用OneWayToSource?我怀疑删除 ModeUpdateSourceTrigger 可能足以使绑定起作用。

标签: wpf mvvm binding


【解决方案1】:

使用ObservableCollection&lt;T&gt; 代替List&lt;T&gt;。它实现了INotifyCollectionChanged 接口。

【讨论】:

  • 啊,这就是问题所在。我的真实代码实际上是在 ViewModel 中使用 BindingList,但在自定义控件中使用 List。更改为在自定义控件中使用 BindingList 也解决了该问题。谢谢伊利亚! :)
猜你喜欢
  • 1970-01-01
  • 2015-02-15
  • 2011-02-22
  • 1970-01-01
  • 2011-02-08
  • 1970-01-01
  • 1970-01-01
  • 2010-10-08
  • 1970-01-01
相关资源
最近更新 更多