将ObversableCollection绑定到DataGrid之后,DataGrid无法显示我的数据。
这张图片显示xx.xaml可以使用Staff_Show。但是这张图片表明数据无法正常显示。
我的计划如下:
<Grid>
<DataGrid x:Name="DataGrid1" CanUserAddRows="False" CanUserDeleteRows="False" CanUserReorderColumns="False"
ItemsSource="{Binding Staff_Show}">
<DataGrid.Columns>
<DataGridTextColumn Header="姓名" Binding="{Binding Name}"/>
<DataGridTextColumn Header="税前金额" Binding="{Binding TB_Sum}"/>
</DataGrid.Columns>
</DataGrid>
</Grid>
和.cs代码:
public ObservableCollection<Staff> Staff_Show = new ObservableCollection<Staff>();
public TaxBefore_Sum(ObservableCollection<Staff> StaffAccept)
{
InitializeComponent();
Staff_Show = StaffAccept;
DataGrid1.DataContext = this.Staff_Show;
}
答案 0 :(得分:1)
this.Datacontext = this
试试这个
修改强>
你必须实现INotifyPropertyChanged接口。
让我们假设你的班级名称是TaxBefore_Sum
public class TaxBefore_Sum : UserControl, INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
protected virtual void OnPropertyChanged(string propertyName)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null) handler(this, new PropertyChangedEventArgs(propertyName));
}
private ObservableCollection<Staff> staff_show = new ObservableCollection<Staff>();
public ObservableCollection<Staff> Staff_Show
{
get { return staff_show;}
set { staff_show = value; this.OnPropertyChanged("Staff_Show"); }
}
public Taxbefore_Sum(ObservableCollection<Staff> StaffAccept)
{
InitializeComponent();
this.DataContext = this;
Staff_Show = StaffAccept;
}
}
希望它有效
答案 1 :(得分:1)
请尝试
DataGrid1.ItemsSource = this.Staff_Show;
它应该工作。另外,你应该添加
AutoGenerateColumns="False"
DataGrid Xaml标记中的。