I am developing a custom WPF control and confused how to use the dependency property. My view model contains 2 properties:
class Customer {
string Name;
string ID;
}
My custom control is responsible for displaying these fields.
Q1: Do I need to define any dependency properties (eg “Name”, “ID”) in my custom control?
Q2: I am using ItemsControl to display a list of Customers. How is the Customer object passed to my custom control? Is it done through the DataContext or do I need to add a “Customer” dependency property in my control and in the xaml, bind “Customer” to “something” (what’s that something)?
<ItemPresenter>
<MyCustomControl Customer="??what should i put here???"/>
</ItemPresender>
Q1. Why do you have a custom control? Ordinarily, you would just create a
UserControl(there is a distinction in WPF betweenUserControland custom control) and bind properties within yourUserControlto properties of your view model. For example (let’s call thisCustomerView):Q2. Through the
DataContext. For example, you might have something like this:Each item generated by the
ItemsControlwill have the related data item set as itsDataContext. Hence, eachCustomerViewwill have the appropriateCustomeras itsDataContext.