在我的wpf應用程序中,我使用Prism庫將我的viewmodel自動裝入我的視圖中。我有這個工作自動綁定視圖和模型的簡單屬性。現在我試圖綁定一個ObservableCollection<T>
數據綁定到DataGrid
沒有運氣。以下是我目前場景的結構。Binding ObservableCollection <T> ItemSource to DataGrid
ConfigurationDetails.cs
public class ConfigurationDetails:BindableBase
{
private int _id;
public int Id { get { return _id; } set { SetProperty(ref _id, value); } }
private string _configFName;
private string _configSName;
private string _configUName;
public string ConfigFName { get { return _configFName; } set { SetProperty(ref _configFName, value); } }
public string ConfigSName { get { return _configSName; } set { SetProperty(ref _configSName, value); } }
public string ConfigUName { get { return _configUName; } set { SetProperty(ref _configUName, value); } }
}
ConfigurationWindowViewModel.cs
public class ConfigurationWindowViewModel : BindableBase
{
public ConfigurationWindowViewModel()
{
ConfigDetails = new ObservableCollection<ConfigurationDetails>();
}
private ObservableCollection<ConfigurationDetails> _configDetails;
public ObservableCollection<ConfigurationDetails> ConfigDetails { get { return _configDetails; } set { SetProperty(ref _configDetails, value); } }
}
ConfigurationWindow.xaml
<UserControl x:Class="MyApp.Views.ConfigurationWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:prism="http://prismlibrary.com/"
prism:ViewModelLocator.AutoWireViewModel="True"
HorizontalContentAlignment="Center">
....
<DataGrid ItemsSource="{Binding ConfigDetails}" AutoGenerateColumns="False">
<DataGrid.Columns>
<DataGridTextColumn Header="F NAME" Width="*" Binding="{Binding Path=ConfigFName}"/>
<DataGridTextColumn Header="S NAME" Width="*" Binding="{Binding Path=ConfigSName}"/>
<DataGridTextColumn Header="U NAME" Width="*" Binding="{Binding Path=ConfigUName}"/>
</DataGrid.Columns>
</DataGrid>
....
</UserControl>
ConfigurationWindow.xaml.cs
public ConfigurationWindow()
{
InitializeComponent();
using (_db = new MyEntities())
{
var configRecords = _db.tblConfigs.ToList().Select(x => new ConfigurationDetails()
{
ConfigFName = x.ConfigFName,
ConfigSName = x.ConfigSName,
ConfigUName = x.ConfigUName,
Id = x.ConfigID
});
model.ConfigDetails = new ObservableCollection<ConfigurationDetails>(configRecords);
//model.ConfigDetails will have records assigned to it when debugged
}
}
}
不過,我仍然沒有看到我的DataGrid
顯示任何記錄。這裏錯過了什麼。我也使用ViewModelLocator.AutoWireViewModel
,它已經完美地工作其他模型屬性。希望在這裏得到一些幫助。
更新 -我有我的ConfigurationWindowViewModel.cs
放在ViewModels
文件夾。對不起,提到。
貴'ConfigurationWindow'實現[IVIEW(http://brianlagunas.com/getting-started-prisms-new-viewmodellocator/)? – slugster
@slugster只有我們的'ViewModel'被放置在我認識的'Views'存在的相同文件夾中時才需要'IView'。否則,如果我們把它放在'ViewModels'文件夾中,'prism'會照顧對嗎? –
那麼你的代碼中的模型來自哪裏(是viewmodel)?順便說一句,爲什麼你在代碼背後得到你的數據? – adminSoftDK