我是wpf的新手,我的数据网格如下,
<DataGrid Grid.Row="0" x:Name="dg1" Grid.Column="0" SelectionChanged="DataGrid_SelectionChanged" ItemsSource="{Binding Path=Articles}" AutoGenerateColumns="False">
<DataGrid.Columns>
<DataGridTextColumn Header="Description" Binding="{Binding Path=Description}" />
</DataGrid.Columns>
</DataGrid>
ViewModel具有属性
public IEnumerable<Article> Articles
{
get
{
return _ArticleList;
}
}
在代码返回错误后,我无法获取所选项目。 无法将“MS.Internal.NamedObject”类型的对象强制转换为“Article”。
private void DataGrid_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
Article Article = (Article)this.dg1.SelectedItems;
}
请提出任何建议如何实现?
答案 0 :(得分:1)
您需要检查是否已选择项目:
private void DataGrid_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
if(this.dg1.SelectedItems.Count > 0){
Article article = (Article)this.dg1.SelectedItems;
}
}
答案 1 :(得分:1)
编辑:
DataGrid.SelectedItems是一个IList。如果你只想选择一个使用DataGrid.SelectedItem&lt; - without s:)
如果要通过Binding设置SelectedItem:
public Article SelectedArticle
{
set
{
this._selectedArticle= value;
OnPropertyChanged("SelectedArticle");
}
get
{
return _selectedArticle;
}
}
XAML
<DataGrid SelectedItem="{Binding SelectedArticle, Mode=OneWayToSource}" />
或作为带有ICommand的按钮的CommandParameter
<Button Command="{Binding EditDataCommand}" CommandParameter="{Binding ElementName=MyGridCtrl, Path=MyDataGrid.SelectedItem}"/>
或具有ICommand
的Button的所有SelectedItems<Button Command="{Binding DeleteDataCommand}" CommandParameter="{Binding ElementName=MyGridCtrl, Path=MyDataGrid.SelectedItems}" >
答案 2 :(得分:0)
希望这有效......
文章_article = ((dgReferences.SelectedItem as DataGridRow).Item as Article);
此致 ArunDhaJ