简体   繁体   中英

How to bind property from Contact class?

I have a class with a property named "ContactInfo" of type Microsoft.Phone.UserData.Contact. I read the contacts from the phone and for each contact I create an object of my class and set the property ContactInfo. All the objects are added to an ObservableCollection that is shown in a LongListSelector.

In C# i can read the elements from the datasource of the ObservableCollection and read the properties from the ContactInfo property of each object but in XAML the data template can't access the properties.

I know that the data source for the LongListSelector is set correctly because removing the data template it shows the object.toString() but setting the data template nothing is shown and in the outpout tab of VS I get the message "System.Windows.Data Error: BindingExpression path error: 'DisplayName' property not found on 'ContactInfo'

Am I forgetting something or is there something set incorrectly?

This is my model:

public class CDContact
{
    public Contact ContactInfo { get; set; }

    public ObservableCollection<CDPhoneNumber> PhoneNumbers{get; set;}

    public CDContact()
    {
        PhoneNumbers = new ObservableCollection<CDPhoneNumber>();
    }
}

This is the data template:

<DataTemplate x:Key="ContactItemTemplate">
    <StackPanel VerticalAlignment="Top" DataContext="ContactInfo" >
            <TextBlock FontWeight="Bold" Text="{Binding Path=DisplayName, Mode=OneWay}" />
    </StackPanel>
</DataTemplate>

Assuming everything else is correctly setup, this should work:

<DataTemplate x:Key="ContactItemTemplate">
    <StackPanel VerticalAlignment="Top" >
        <TextBlock FontWeight="Bold" Text="{Binding Path=ContactInfo.DisplayName, Mode=OneWay}" />
    </StackPanel>
</DataTemplate>

This part seems wrong :

<StackPanel VerticalAlignment="Top" DataContext="ContactInfo" >

Try it this way instead :

<StackPanel VerticalAlignment="Top" DataContext="{Binding ContactInfo}" >

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM