【发布时间】:2020-03-30 17:12:03
【问题描述】:
我是 WPF 世界的新手。我真的需要帮助。我正在尝试将 ObservableCollection 与 DataGrid 绑定,但它不起作用。我只想使用 XAML ItemSource="{Binding}" 进行绑定。我在 MVVM 中完成所有这些工作。
还有一件事,View 将如何连接到 ViewModel?我必须在我的 View XAML 文件中进行任何更改。
你能建议我从哪里可以完全学习 WPF。
项目名称是 - MVVMGrid
模型 - Data.cs
public class Data :INotifyPropertyChanged
{
private string _name;
private string _country;
public string Name
{
get { return _name; }
set { _name= value;
OnPropertyChange("Name");
}
}
public string Country
{
get { return _country; }
set { _country= value;
OnPropertyChange("Country");
}
}
protected void OnPropertyChange(string name = null)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(name));
}
public event PropertyChangedEventHandler PropertyChanged;
}
ViewModel - DataView.cs
public class DataView
{
public DataView()
{
FetchGrid();
}
public static ObservableCollection<Data> FetchGrid()
{
var load = new ObservableCollection<Data>();
load.Add(new Data { Name = "Raja", Country = "INDIA" });
load.Add(new Data { Name = "Ram", Country = "India" });
load.Add(new Data { Name = "Rohan", Country = "USA" });
load.Add(new Data { Name = "Roy", Country = "TURKEY" });
return load;
}
}
查看 - MainWindow.xaml
<Window x:Class="MVVMGrid.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:Grid"
mc:Ignorable="d"
Title="MainWindow" Height="450" Width="800">
<Grid>
<DataGrid ItemsSource="{Binding Path= FetchGrid}" AutoGenerateColumns="False" >
<DataGrid.Columns>
<DataGridTextColumn Header="Name" Binding="{Binding Name}"/>
<DataGridTextColumn Header="Country" Binding="{Binding Country}"/>
</DataGrid.Columns>
</DataGrid>
</Grid>
</Window>
【问题讨论】:
标签: wpf