我在 wrt 数据绑定下面的 mvvm 模式中做错了什么?
我看到的是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;
}