2013-01-22 72 views
0

我有一個listView初始化問題。在的ListView的的.xaml部分如下,更改窗口初始化的MVVM WPF列表視圖項目

<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 
    } 
... 

回答

2

這就是ViewModel存在的原因:它們可以透明地將模型中的值轉換爲更適合綁定的值。

您應該在MainWindowViewModel上公開CategoryList屬性並直接綁定該屬性。然後,您可以通過在RecordModel屬性setter處理的RecordModel.CategoryList值來填充它:

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; } 
} 
+0

謝謝,我會試試看現在。 – mechanicum

+0

完全按照我的意願工作。 – mechanicum

相關問題