我在做什麼錯誤的數據綁定下方的mvvm模式?將datagrid綁定到viewmodel
我看到的是一個DataGrid
顯示一個額外的列和一個額外的行(都是空的),爲什麼?
而且:如何讓我的視圖默認選擇第一項?
視圖模型:
public class Instance { public string Name { get; set; } }
public class BaseData
{
public ObservableCollection<Instance> Instances { get { return instances; } }
public BaseData()
{
var bw = new BackgroundWorker();
bw.DoWork += new DoWorkEventHandler(fetch);
bw.RunWorkerAsync();
bw.RunWorkerCompleted += new RunWorkerCompletedEventHandler(fetched);
}
void fetch(){...}
void fetched(..){... // raise event 'Fetched' to the view }
}
視圖(XAML):
<DataGrid AutoGenerateColumns="False" x:Name="dgInstances" ItemsSource="{Binding Instances}">
<DataGrid.Columns>
<DataGridTextColumn Header="Instance" Binding="{Binding Path=Name, Mode=OneWay}" />
</DataGrid.Columns>
</DataGrid>
視圖(代碼隱藏):
BaseData BaseData;
public MainWindow()
{
InitializeComponent();
Loaded += delegate
{
BaseData = new BaseData();
BaseData.Fetched += basedata_fetched;
};
}
void basedata_fetched(...)
{
DataContext = BaseData;
}
正確。這樣的設計有多奇怪。 – Gerard
:),是的,他們希望你配置什麼不是 –