views:

1046

answers:

1

I've created two UserControls, the first of which displays a list of objects, the second of which displays details about an object that is selected from the first. I've created a dependency property on the first control and am binding each UserControl to an object declared in my Resources collection. I've seen blog posts describing this, but cannot seem to get it to work. I am getting a XamlParseException. The funny thing is the exception only occurs when I set the binding Mode=TwoWay on my first UserControls. Here's the code...

Page.xaml

<UserControl.Resources>
    <local:Item x:Key="SelectedItem" />
</UserControl.Resources>

...

<controls:ItemList 
    SelectedItem="{Binding Mode=TwoWay, Source={StaticResource SelectedItem}}">      
</controls:ItemList >

...

<controls:ItemDetails
    DataContext="{Binding Source={StaticResource SelectedItem}}">      
</controls:ItemDetails>

ItemList.xaml.cs

public partial class ItemList: UserControl
{
    public ItemList()
    {
     InitializeComponent();
    }

    public static readonly DependencyProperty SelectedItemProperty =
     DependencyProperty.Register("SelectedItem", typeof(Item), typeof(ItemList), new PropertyMetadata(new Item()));
    public Item SelectedItem
    {
     get { return (Item )GetValue(SelectedItemProperty ); }
     set { SetValue(SelectedItemProperty , value); }
    }

Any suggestions are welcome!

+1  A: 

Your Xaml is incorrect, from the looks of it. You are missing a property that you need to bind to for two-way. You are saying that you want to bind to object defined in source, but you don't specify a property of that resource to bind to. In this case, the SelectedItem resource is an object of type Item ... you need to bind to property of Item. So if item has a property named value, your Xaml could look like this:

SelectedItem="{Binding Value, Source={StaticResource SelectedItem}, Mode=TwoWay}"

Try this instead:

SelectedItem="{Binding SelectedItem, Mode=TwoWay}"

ib.

Ireney Berezniak
Great explanation. Thanks!
Kevin Babcock