我的datagrid给了我正确的行数,但行中没有数据。
这是我的WPF代码
<Grid AllowDrop="True">
<DataGrid x:Name="dataGrid" AutoGenerateColumns="False" ItemsSource="{Binding}">
<DataGrid.Columns>
<DataGridTextColumn x:Name="c1" Header="Full Name" Binding="{Binding FullNames}" Width="200"/>
<DataGridTextColumn x:Name="c2" Header="Age" Binding="{Binding Ages}" Width="200"/>
</DataGrid.Columns>
</DataGrid>
<Button x:Name="button" Content="Button" HorizontalAlignment="Left" Margin="128,296,0,3" Width="75" Click="button_Click"/>
</Grid>
这是我背后的代码
public partial class MainWindow : Window
{
public string FullNames { get; set; }
public int Ages { get; set; }
public MainWindow()
{
InitializeComponent();
this.dataGrid.DataContext = GetInfo();
}
private List<string> GetInfo()
{
List<string> list = new List<string>();
List<int> listAge = new List<int>();
list.Add(FullNames = "User 1" );
list.Add(FullNames = "User 2");
list.Add(FullNames = "User 3");
list.Add(FullNames = "User 4");
list.Add(FullNames = "User 5");
listAge.Add(Ages = 35);
listAge.Add(Ages = 34);
listAge.Add(Ages = 10);
listAge.Add(Ages = 8);
listAge.Add(Ages = 4);
return list;
}
}
提前致谢。顺便说一句,我必须写这个,因为stackoverflow说我需要更多的细节。我以为我写的那个小,代码就够了,但我猜不是,哈哈,
答案 0 :(得分:0)
在分配这些属性时,UI不会更新,以更新UI: 1)使用ObservableCollection,这是一个列表,用于在添加或删除项目时更新UI。 2)定义一个类,如:
public class Person: DependencyObject
{
public string name
{
get { return (string)GetValue(nameProperty); }
set { SetValue(nameProperty, value); }
}
// Using a DependencyProperty as the backing store for name. This enables animation, styling, binding, etc...
public static readonly DependencyProperty nameProperty =
DependencyProperty.Register("name", typeof(string), typeof(Person), new PropertyMetadata("Fred"));
public int age
{
get { return (int)GetValue(ageProperty); }
set { SetValue(ageProperty, value);
if (fireshower != null)
fireshower.Value = value;
}
}
// Using a DependencyProperty as the backing store for age. This enables animation, styling, binding, etc...
public static readonly DependencyProperty ageProperty =
DependencyProperty.Register("age", typeof(int), typeof(RuleTileInfo), new PropertyMetadata(0));
}
这对您来说有两件事:它会使您的代码更容易扩展,因为信息整齐有序,如果人员年龄改变,UI将收到有关该更新的更新。 3)虽然可以将datacontext设置为Observable集合并使用ItemsSource = {Binding},但最好将UI中显示的所有对象放入视图模型,并将窗口的datacontext设置为视图模型。然后绑定到该视图模型中列表的名称。适用于案例的VM可能是:
public class WindowVM: DependencyObject
{
public ObservableCollection<Person> People
{
get { return (string)GetValue(PeepleProperty); }
set { SetValue(PeopleProperty, value); }
}
// Using a DependencyProperty as the backing store for name. This enables animation, styling, binding, etc...
//ect
}
这将有助于整理您的计划,使其更易于理解和更易于维护。提示:依赖属性很麻烦,手动输入,使用它们的片段(键入propdp和命中标签两次,填写字段击中标签以在它们之间切换,VS将为您填写冗余信息)