开发者

View Model, Dependency Properties Confusion

开发者 https://www.devze.com 2023-03-11 17:19 出处:网络
I am developing a custom WPF control and confused how to use the dependency property. My view model contains 2 properties:

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;
}
开发者_JAVA百科

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 between UserControl and custom control) and bind properties within your UserControl to properties of your view model. For example (let's call this CustomerView):

<UserControl ...>
    <StackPanel>
        <TextBlock Text="{Binding ID}"/>
        <TextBox Text="{Binding Name}"/>
    </StackPanel>
</UserControl>

Q2. Through the DataContext. For example, you might have something like this:

<ItemsControl ItemsSource="{Binding Customers}">
    <ItemsControl.ItemTemplate>
        <DataTemplate>
            <local:CustomerView/>
        </DataTemplate>
    </ItemsControl.ItemTemplate>
</ItemsControl>

Each item generated by the ItemsControl will have the related data item set as its DataContext. Hence, each CustomerView will have the appropriate Customer as its DataContext.

0

精彩评论

暂无评论...
验证码 换一张
取 消