Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/wpf/12.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 强制刷新依赖项属性_C#_Wpf_Dependency Properties_Itemssource - Fatal编程技术网

C# 强制刷新依赖项属性

C# 强制刷新依赖项属性,c#,wpf,dependency-properties,itemssource,C#,Wpf,Dependency Properties,Itemssource,我想强制列表框的绑定刷新其内容。 我的列表框绑定到依赖项属性: <ListBox ... DataContext="{Binding ElementName=_this}" ItemsSource="{Binding Path=MyList}"/> 例如,当我以调用DependencyProperty MyList get的方式按下按钮时,我希望刷新列表框内容。您可以将MyList设置为,或其他实现 然后,如果更改MyList的内容,列表框将自动更新 在这种情况下,您甚至不需要

我想强制列表框的绑定刷新其内容。 我的列表框绑定到依赖项属性:

<ListBox ... DataContext="{Binding ElementName=_this}" ItemsSource="{Binding Path=MyList}"/>

例如,当我以调用DependencyProperty MyList get的方式按下按钮时,我希望刷新列表框内容。

您可以将MyList设置为,或其他实现

然后,如果更改MyList的内容,列表框将自动更新

在这种情况下,您甚至不需要将
MyList
声明为依赖项属性。一个简单的只读属性就足够了:

public ObservableCollection<MyItem> MyList { get; }
    = new ObservableCollection<MyItem>();
publicobservableCollection MyList{get;}
=新的ObservableCollection();
使用作为要在列表框中显示的项目的容器。这将在添加或删除项时自动触发控件刷新

由于您现在不再需要创建新集合(只刷新其内容),因此可以为此使用常规的C#属性

就我个人而言,我会把它抽象出来

private ObservableCollection<MyItem> _mylist = new  ObservableCollection<MyItem>();
public IEnumerable<MyItem> MyList => _mylist;
控件仍将更新,因为它检测到MyList实现了INotifyCollectionChanged,即使它只是声明为IEnumerable

决不能对数据绑定源使用DependencyProperty-对于任何更新其值的属性,常规属性与INotifyPropertyChanged相结合是首选的方法。将MVVM模式作为一种将用户界面与代码的其余部分分离的方法

_myList.Clear();
_mylist.Add( ... );