Data Binding to Objects in WPF Card View
4 Sep 2020 / 6 minutes to read
The CardView control can also support data-binding to objects. The following example shows this.
-
Create a class that act as a model for CardViewItem as follows.
public class Contact : IDataErrorInfo { [Required] public string Name { get; set; } [Range(1, 100)] public int Age { get; set; } #region IDataErrorInfo Members public string Error { get { return this[String.Empty]; } } public string this[string columnName] { get { string result = String.Empty; if (columnName == "Name") { if (string.IsNullOrEmpty(this.Name)) { result = "Name is mandatory"; } } if (columnName == "Age") { if (this.Age < 1 || this.Age > 100) { result = "Invalid Age"; } } return result; } } #endregion }
-
Create a ViewModel class and initialize the items as follows.
public class ViewModel { public ObservableCollection<Contact> Contacts { get; set; } public ViewModel() { Contacts = new ObservableCollection<Contact>(); PopulateData(); } private void PopulateData() { Contacts.Add(new Contact() { Name = "John", Age = 26 }); Contacts.Add(new Contact() { Name = "Mark", Age = 25 }); Contacts.Add(new Contact() { Name = "Steven", Age = 26 }); } }
-
Create a ViewModel instance and use it as DataContext for the root window.
<Window.DataContext> <local:ViewModel/> </Window.DataContext>
-
Configure the ItemTemplate and HeaderTemplate for the CardView control.
<syncfusion:CardView ItemsSource="{Binding Contacts}" >
<syncfusion:CardView.ItemTemplate>
<DataTemplate >
<ListBox>
<ListBoxItem>
<StackPanel Orientation="Horizontal">
<TextBlock Text="Name:"/>
<TextBlock Text="{Binding Name}" Margin="5,0,0,0"/>
</StackPanel>
</ListBoxItem>
<ListBoxItem>
<StackPanel Orientation="Horizontal">
<TextBlock Text="Age :"/>
<TextBlock Text="{Binding Age}" Margin="5,0,0,0"/>
</StackPanel>
</ListBoxItem>
</ListBox>
</DataTemplate>
</syncfusion:CardView.ItemTemplate>
<syncfusion:CardView.HeaderTemplate>
<DataTemplate>
<TextBlock Text="{Binding Name}"/>
</DataTemplate>
</syncfusion:CardView.HeaderTemplate>
</syncfusion:CardView>
This creates the following CardView control.
Was this page helpful?
Yes
No
Thank you for your feedback!
Thank you for your feedback and comments. We will rectify this as soon as possible!
An unknown error has occurred. Please try again.
Help us improve this page