我有一个UserControl ......
XAML:
<UserControl x:Name="ClientsListControl" ....... >
<Grid>
<ListBox Margin="10" DisplayMemberPath="Name"
Name="profilesListBox"
ItemsSource="{Binding ElementName=ClientsListControl, Path=Items}" />
</Grid>
</UserControl>
代码背后:
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();
}
}
...和窗口。
问题是:
1)这有效:
<cm:ClientsList x:Name="clientsList" Items="{Binding}" />
<TextBox Width="100" Height="20" Name="Bla" Text="{Binding ElementName=clientsList, Path=ListBox.SelectedItem.Name}" />
2)这不起作用:
<cm:ClientsList x:Name="clientsList" Items="{Binding}" />
<TextBox Width="100" Height="20" Name="Bla" Text="{Binding ElementName=clientsList, Path=SelectedItem.Name}" />
答案 0 :(得分:0)
使SelectedItem
成为依赖项属性,并将ListBox的SelectedItem
属性绑定到它,就像使用Items
一样。
XAML:
<Grid>
<ListBox Margin="10" DisplayMemberPath="Name"
Name="profilesListBox"
ItemsSource="{Binding ElementName=ClientsListControl, Path=Items}"
SelectedItem="{Binding ElementName=ClientsListControl, Path=SelectedItem}"/>
</Grid>
代码背后:
public static DependencyProperty SelectedItemProperty =
DependencyProperty.Register("SelectedItem", typeof(ClientViewModel), typeof(ClientsList));
public ClientViewModel SelectedItem
{
get { return (ClientViewModel)GetValue(SelectedItemProperty); }
set { SetValue(SelectedItemProperty, value); }
}