I have a window in which I want to autogenerate ObservableCollection from another class. When setting it up in back-end, everything works properly:
XAML
<DataGrid Name="ResidenceGrid" AutoGenerateColumns="True"/>
CS
public ResidenceWindow()
{
InitializeComponent();
ResidenceGrid.ItemsSource = Manager.ResidenceList;
}
But the moment I try to do it all in xaml, the DataGrid appears blank:
XAML
<DataGrid Name="ResidenceGrid" ItemsSource="{Binding Path=Manager.ResidenceList, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" AutoGenerateColumns="True"/>
CS
public ResidenceWindow()
{
InitializeComponent();
}
The ObservableCollection called from another class just in case:
static class Manager
{
public static ObservableCollection<Residence> ResidenceList { get; set; } = new ObservableCollection<Residence>();
}
Any idea what I'm missing here?
If you want to use Binding, you need to set DataContext inside your ResidenceWindow.
Ex:
public ResidenceWindow()
{
InitializeComponent();
this.DataContext = Manager;
}
https://www.wpf-tutorial.com/data-binding/using-the-datacontext/
You can bind to the static Manager.ResidenceList
property like this:
<DataGrid Name="ResidenceGrid" ItemsSource="{x:Static local:Manager.ResidenceList}" AutoGenerateColumns="True"/>
And there is no reason to set the Mode
of the binding for the ItemsSource
property to TwoWay
nor set the UpdateSourceTrigger
to PropertyChanged
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.