0

在我的项目中,我想在用户控件上显示一个列表。为此,我有一个 CategoryView 用户控件和一个 ListView 控件,我想在其中显示列表。和 CategoryViewModel。在 ViewModel 上,我有一个列表 - 属性,我还引发了属性更改事件。

public class CategoryViewModel : NotificationObject
{
    private List<string> categoryList;

    public List<string> CategoryList
    {
        get
        {
            return this.categoryList;
        }
        set
        {
            this.categoryList = value;
            this.RaisePropertyChanged("CategoryList");
        }
    }
}

此列表绑定到视图中的 ListView 元素。

如果我更改 CategoryViewModel 中的列表,它可以正常工作并引发属性更改事件。如果我从 MainWindowViewModel 更改列表。未引发任何属性 Changed 事件,并且不会更新视图。我该怎么做?

在 MainWindowViewModel 上,我更改了 CategoryList。列表将正确填写。

CategoryViewModel categoryViewModel = new CategoryViewModel();
categoryViewModel.CategoryList = logger.ReadLogfile(this.logFileName).ToList();
4

1 回答 1

1

你似乎有些困惑。你ListViewCategoryView UserControl. 它的ItemsSource属性只能是数据绑定到一个集合,所以很明显,在主视图模型中更改集合时CategoryViewModel,只有一个会影响ListView.

从您的代码看来,CategoryViewModel被设置为DataContextUserControl因此主视图模型中的集合不会连接到ListView。如果您想将数据从 绑定ListView到主视图模型中的集合,那么您需要使用 aRelativeSource Binding来代替:

<ListView ItemsSource="{Binding SomeCollection, RelativeSource={RelativeSource 
    AncestorType={x:Type YourPrefix:YourParentType}}}" ... />

即便如此,现在你的收藏CategoryViewModel将不再连接,所以你最好确定你想在这里做什么。

于 2014-03-14T16:52:41.027 回答