[英]For a user control with a listbox, how can I expose the selected item to a parent page?
我有一个简单的用户控件,它在AutoCompleteBox周围包含了一些逻辑。 这个问题可能适用于任何ItemsControl控件,例如下拉列表或列表框。
<UserControl>
<Grid Background="White">
<sdk:AutoCompleteBox Name="myACB" ItemsSource="{Binding myData}" />
</Grid>
</UserControl>
我想在使用控件的父项中公开AutoCompleteBox的SelectedItem
属性。 我的用户控件虽然使用视图模型作为其数据上下文。 否则,我想我可以将SelectedItem绑定到用户控件的依赖项属性。
我需要能够让父级检测到子级自动完成框所选项目何时更改。 我该怎么办?
只需在UserControl中创建一个依赖项属性 ,并将其与您的内部控件绑定,如下所示:
1)在CustomControl中添加一个依赖项属性:
public System.Collections.IEnumerable ItemsSource
{
get { return (System.Collections.IEnumerable)GetValue(ItemsSourceProperty); }
set { SetValue(ItemsSourceProperty, value); }
}
// Using a DependencyProperty as the backing store for ItemsSource. This enables animation, styling, binding, etc...
public static readonly DependencyProperty ItemsSourceProperty =
DependencyProperty.Register("ItemsSource", typeof(System.Collections.IEnumerable), typeof(UserControl1), new UIPropertyMetadata(null));
2)将内部控件与dependency属性绑定:
<UserControl ... x:Name="control" ... >
<ListBox ItemsSource="{Binding ElementName=control, Path=ItemsSource}" />
编辑 :实现ItemsSource
如果您尝试通过这种方式,它可以更新用户控件中的属性:
<ListBox SelectedItem="{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=UserControl}, Mode=OneWayToSource, Path=ThePropertyInMyUserControl}"/>
然后,ThePropertyInMyUserControl可以成为其他依赖项属性。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.