tags:

views:

23

answers:

1

I have a UserControl...

XAML:

<UserControl x:Name="ClientsListControl" ....... >
<Grid>
    <ListBox Margin="10" DisplayMemberPath="Name"
             Name="profilesListBox" 
             ItemsSource="{Binding ElementName=ClientsListControl, Path=Items}" />
</Grid>
</UserControl>

Code behind:

public partial class ClientsList : UserControl
{
    public static DependencyProperty ItemsProperty =
        DependencyProperty.Register("Items", typeof(ClientsListViewModel), typeof(ClientsList));

    public ClientsListViewModel Items
    {
        get
        {
            return (ClientsListViewModel) GetValue(ItemsProperty);
        }
        set
        {
            SetValue(ItemsProperty, value);
        }
    }

    public ListBox ListBox
    {
        get
        {
            return profilesListBox;
        }
    }

    public ClientViewModel SelectedItem
    {
        get
        {
            return (ClientViewModel) profilesListBox.SelectedItem;
        }
    }

    public ClientsList()
    {
        InitializeComponent();
    }
}

... and Window.

The problem is:

1) this works:

<cm:ClientsList x:Name="clientsList" Items="{Binding}" />
<TextBox Width="100" Height="20" Name="Bla" Text="{Binding ElementName=clientsList, Path=ListBox.SelectedItem.Name}" />

2) this doesn't work:

<cm:ClientsList x:Name="clientsList" Items="{Binding}" />
<TextBox Width="100" Height="20" Name="Bla" Text="{Binding ElementName=clientsList, Path=SelectedItem.Name}" />
A: 

Make SelectedItem a dependency property and bind the SelectedItem property of the ListBox to it just like you did with Items.

XAML:

<Grid>
    <ListBox Margin="10" DisplayMemberPath="Name"
             Name="profilesListBox" 
             ItemsSource="{Binding ElementName=ClientsListControl, Path=Items}"
             SelectedItem="{Binding ElementName=ClientsListControl, Path=SelectedItem}"/>
</Grid>

Code behind:

public static DependencyProperty SelectedItemProperty =
        DependencyProperty.Register("SelectedItem", typeof(ClientViewModel), typeof(ClientsList));

public ClientViewModel SelectedItem
{
    get { return (ClientViewModel)GetValue(SelectedItemProperty); }
    set { SetValue(SelectedItemProperty, value); }
}
Quartermeister
Nice solution. Thank you!
JooLio