0

我对 listView 初始化有疑问。listView的 .xaml 部分如下所示,

<ListView x:Name="categoryListView" HorizontalAlignment="Left" Width="129" Height="180" 
              ItemsSource="{Binding Path=RecordModel.CategoryList}" 
              DisplayMemberPath="RecordModel.CategoryList" 
              SelectedValue="{Binding Path=RecordModel.RecordTitle}"
              VerticalAlignment="Top">

我在RecordModel.CategoryList中有一个字符串路径列表,但我需要在窗口初始化时更改该列表。部分视图模型如下。我在哪里可以添加代码来更改列表,以便 listView 在开始时获取更改的列表项?

public class MainWindowViewModel : ViewModelBase
{
...
private RecordModel _recordModel;
private ICommand _addCategoryCommand;
...

public MainWindowViewModel()
{
 _recordModel = new RecordModel();
}
public RecordModel RecordModel
{
  get { return _recordModel; }
  set { _recordModel = value; }
}
...
public ICommand AddCategoryCommand
{
 get
  {
   if (_addCategoryCommand == null)
       _addCategoryCommand = new AddCat ();
     return _addCategoryCommand;
  }
}

public class AddCat : ICommand
{
  public bool CanExecute(object parameter) { return true; }
  public event EventHandler CanExecuteChanged;
  public void Execute(object parameter)
  {
    MainWindowViewModel mainWindowViewModel = (MainWindowViewModel)parameter;
    ...
    //Do things with mainWindowViewModel and the variables it has
  }
...
4

1 回答 1

2

这就是 ViewModel 存在的原因:以便它们可以透明地将模型中的值转换为更适合绑定的值。

您应该在该上公开一个CategoryList属性MainWindowViewModel并直接在其上绑定。然后,您可以通过处理属性设置器RecordModel.CategoryList中的值来填充它:RecordModel

public class MainWindowViewModel : ViewModelBase
{
    private RecordModel _recordModel;

    public MainWindowViewModel()
    {
        RecordModel = new RecordModel(); // set the property not the field
    }

    public RecordModel RecordModel
    {
        get { return _recordModel; }
        set {
            _recordModel = value;
            // populate CategoryList here from value.CategoryList
        }
    }

    public UnknownType CategoryList { get; }
}
于 2013-01-22T15:23:50.320 回答