我喜欢在应用程序和自定义Usercontrol之间共享列表。 我使用IEnumerable作为附加属性为自定义UserControl内的Listbox提供列表。然后ListBox接收附加属性作为ItemsSource。这项工作到目前为止。但是当主机列表更改时,usercontrol中的列表应该更新。我怎样才能做到这一点? 当前代码设置Usercontrol列表,但是当主机更改列表时,附加属性将不会更新。
使用UserControl的主机有一个ComboBox,它应该与UserControl的ListBox共享其ItemsSource
public ObservableCollection<Person> PersonList
{
get;
set;
}
主机的Xaml将ComboBox绑定到集合:
<ComboBox x:Name="combobox1" Width="200" ItemsSource="{Binding PersonList}" DisplayMemberPath="Name" SelectedIndex="0" IsEditable="True"></ComboBox>
放置在主机内的Usercontrol通过附加属性接收集合。绑定看起来很重,但似乎没问题:
<myUserCtrl:AdvEditBox
...
prop:DynamicListProvider.DynamicList="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type Window}},
Path=DataContext.PersonList}">
...
</myUserCtrl:AdvEditBox
附加属性有一个回调,目前只调用一次:
class DynamicListProvider : DependencyObject
{
public static readonly DependencyProperty DynamicListProperty = DependencyProperty.RegisterAttached(
"DynamicList",
typeof(IEnumerable),
typeof(DynamicListProvider),
new FrameworkPropertyMetadata(null, OnDynamicListPropertyChanged)));
public static IEnumerable GetDynamicList(UIElement target) {..}
public static void SetDynamicList(UIElement target, IEnumerable value) {..}
private static void OnDynamicListPropertyChanged(DependencyObject o, DependencyPropertyChangedEventArgs e)
{
if (e.NewValue != null && o is FrameworkElement)
{
...
}
}
每当主机的PersonList发生更改时,都应调用OnDynamicListPropertyChanged()。我是否必须在附加属性中放置INotifyCollectionChanged?如果是这样,在哪里以及如何?
答案 0 :(得分:1)
这是我的解决方案:
1)usercontrol的dp:
public static readonly DependencyProperty SelectionListProperty = DependencyProperty.Register(
"SelectionList",
typeof(ObservableCollection<MyList>),
typeof(MyUserControl),
new UIPropertyMetadata(null));
(..添加属性get / set wrapper)
2)在List上设置UserControls ItemsSource,例如
_combobox.ItemsSource = SelectionList;
3)主持人拥有该名单。在实例化usercontrol的类中添加数据及其属性。就我而言,我使用readonly / oneway binding。
ObservableCollection<MyList> _bigList= new ObservableCollection<MyList>();
public ObservableCollection<MyList> BigList
{
get { return _bigList; }
}
4)在xaml中设置绑定
<myctrl:MyUserControl
SelectionList="{Binding BigList, Mode=OneWay}"
...
/>
5)现在,无论何时修改_biglist,都要在“BigList”上调用PropertyChangedEventHandler。这将通知绑定设置的UserControl的SelectionList并调用BigList get {}。希望你能清楚。