在DelegateCommand方法中更新属性后,UI不会更新

时间:2016-03-07 14:13:48

标签: c# wpf mvvm

我有一个窗口(从主窗口ViewModel打开),其中包含一个ListView和一个按钮。此ListView的内容绑定到ObservableCollection。

<ListView ItemsSource="{Binding FoundElements}" Grid.Row="2" />

按钮触发命令

<Button Command="{Binding SearchCommand}" Margin="10 0 0 0">
    <Button.Content>
        <TextBlock Text="Search" VerticalAlignment="Center" />
     </Button.Content>
 </Button>

在ViewModel中,我有绑定的DelegateCommand和Property。

private ObservableCollection<String> _foundElements;

public ObservableCollection<string> FoundElements
{
     get { return _foundElements; }
     set { _foundElements= value; OnPropertyChanged("FoundElements"); }
}

ICommand _searchCommand;

public ICommand SearchCommand
{
    get { return _searchCommand; }
    set { _searchCommand = value; }
}

在构造函数中:

this.SearchCommand = new DelegateCommand(o => SearchMethod());

如果我在构造函数中修改属性,则会显示带有modified属性的窗口(即列表中有元素),但如果我在DelegateCommand方法中修改属性,按下按钮后,它不会(我检查并输入方法)。

this.FoundElements = new ObservableCollection<String>() { "a", "a", "a", "a", "a", "a", "a", "a" };

窗口在主窗口ViewModel

中创建
SubWindow w = new SubWindow();
w.Owner = System.Windows.Application.Current.MainWindow;
w.Show();

在SubWindow代码隐藏中,我分配了DataContext

public SubWindow()
{
    this.DataContext = new SubWindowViewModel();

    InitializeComponent();
}

这是OnPropertyChanged:

public event PropertyChangedEventHandler PropertyChanged;

protected void OnPropertyChanged(string name)
{
    PropertyChangedEventHandler handler = PropertyChanged;
    if (handler != null)
    {
        handler(this, new PropertyChangedEventArgs(name));
    }
}

切换DataContext赋值和InitialiseComponent()我在控制台中收到此错误:

System.Windows.Data Information: 10 : Cannot retrieve value using the binding and no valid fallback value exists; using default instead. BindingExpression:Path=FoundElements; DataItem=null; target element is 'ListView' (Name=''); target property is 'ItemsSource' (type 'IEnumerable')

创建窗口/更新Dispatcher中的属性,如:

System.Windows.Application.Current.Dispatcher.BeginInvoke(new Action(() =>
{
    // code
}));

没有任何影响。

有什么想法吗?

感谢。

1 个答案:

答案 0 :(得分:0)

ViewModel必须实现INotifyPropertyChanged。就这么简单。该死,我失去了一个下午。