簡體   English   中英

如何將數據提供給視圖模型?

[英]How to feed the data to the view model?

我已經嘗試創建POC相當長時間了,試圖簡化眾多博客上的示例。 不知何故,我看不到我所缺少的。

我具有此XAML結構,並且已將文本塊的內容綁定到視圖模型中的屬性Alpha

<Window ... >
  <Window.DataContext>
    <local:ViewModel></local:ViewModel>
  </Window.DataContext>
  <Grid>
    ...
    <DataGrid ...>
      <DataGrid.Columns>
        <DataGridTemplateColumn>
          <DataGridTemplateColumn.CellTemplate>
            <DataTemplate>
              <TextBlock Text="{Binding Alpha}"></TextBlock>
            </DataTemplate>
          </DataGridTemplateColumn.CellTemplate>
        </DataGridTemplateColumn>
      </DataGrid.Columns>
    </DataGrid>
  </Grid>
</Window>

視圖模型非常簡單,目前僅包含一個屬性。

class ViewModel
{
  public String Alpha { get; set; }
}

當然,我們需要以某種方式將數據提供給視圖模型。 因此,我為假值創建了一個簡單的吸氣劑。

public partial class MainWindow : Window
{
  public MainWindow()
  {
    InitializeComponent();
  }

  private static IEnumerable<String> GetFakes()
  {
    yield return "beep";
    yield return "boop";
  }
}

我還沒有找到任何清晰的示例來說明如何將這些數據饋送到視圖模型(或者如何使視圖模型獲取數據)。 請注意,要顯示的數據是靜態的,並且不會一開始就更改,因此我不需要任何通知程序(或者會嗎?),因為所有信息都已准備好在初始化時進行。

您應該具有主視圖模型,其中包含您的子視圖模型的列表。

class MainViewModel
{
    public ObservableCollection<DataGridRowViewModel> Items
    {
        get;
        set;
    }

    public MainViewModel(){
        Items = new ObservableCollection<DataGridRowViewModel>{
            new DataGridRowViewModel("Beep"),
            new DataGridRowViewModel("Meep")
        };
    }
}

class DataGridRowViewModel
{
    public string Alpha {get;set;}

    public DataGridRowViewModel(string alpha){
        Alpha = alpha;
    }
}

在您的數據網格中,應該綁定Items屬性,請參見ItemsSource

<Window ... >
  <Window.DataContext>
    <local:MainViewModel/>
  </Window.DataContext>
  <Grid>
    ...
    <DataGrid ... ItemsSource="{Binding Items}">
      <DataGrid.Columns>
        <DataGridTemplateColumn>
          <DataGridTemplateColumn.CellTemplate>
            <DataTemplate>
              <-- This DataTemplate applies TO DataGridRowViewModel -->
              <TextBlock Text="{Binding Alpha}"></TextBlock>
            </DataTemplate>
          </DataGridTemplateColumn.CellTemplate>
        </DataGridTemplateColumn>
      </DataGrid.Columns>
    </DataGrid>
  </Grid>
</Window>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM