在运行时更改ObservableCollection以进行绑定
本文关键字:绑定 ObservableCollection 运行时 | 更新日期: 2023-09-27 18:11:22
我正在为我的ObservableCollection中的每个项目生成Grid。现在我希望能够在运行时更改源集合,我不确定需要做什么。
这是我的XAML:<Window.Resources>
<c:GraphicsList x:Key="GraphicsData" />
</Window.Resources>
...
...
<ItemsControl x:Name="icGraphics" ItemsSource="{Binding Source={StaticResource GraphicsData}}" >
<ItemsControl.ItemTemplate>
<DataTemplate>
<Grid Tag="{Binding id}" Margin="15,0,15,15">
<Label Grid.Row="0" Content="{Binding name}"/>
</Grid>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
和c#:
myCollection1 = this.FindResource("GraphicsData") as GraphicsList;
myCollection1:
public class GraphicsList : ObservableCollection<Graphics>
{
public GraphicsList()
{
}
}
图形类:class Graphics: INotifyPropertyChanged
{
// some properties not important
}
这是我的代码的简化版本,但它的工作原理,我基本上想改变源集合myCollection1到myCollection2(这是相同的类只是不同的列表)。我该怎么做呢?
您可以按如下方式添加或删除集合中的项
var dresource = this.Resources["GraphicsData"] as GraphicsList;
dresource.Add(new Graphics() { Name = "New Entry" });
但是使用StaticResource,您不能将新集合分配给ResourceDictionary中的一个。
理想情况下,如果你想分配一个全新的集合,你应该使用ViewModel和bind Collection。
你的主窗口类或视图模型应该实现INotifyPropertyChanged接口
示例代码 public partial class MainWindow : Window, INotifyPropertyChanged
{
private GraphicsList _graphicsData;
public MainWindow()
{
InitializeComponent();
DataContext = this;
this.Loaded += MainWindow_Loaded;
}
public GraphicsList GraphicsData
{
get { return _graphicsData; }
set
{
if (Equals(value, _graphicsData)) return;
_graphicsData = value;
OnPropertyChanged("GraphicsData");
}
}
void MainWindow_Loaded(object sender, RoutedEventArgs e)
{
//var resource = this.Resources["GraphicsData"] as GraphicsList;
var resource = new GraphicsList();
resource.Add(new Graphics(){Name = "Some new Collection of data"});
this.GraphicsData = resource;
}
public event PropertyChangedEventHandler PropertyChanged;
[NotifyPropertyChangedInvocator]
protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null) handler(this, new PropertyChangedEventArgs(propertyName));
}
}
And Your Xaml
<Grid>
<ListBox ItemsSource="{Binding GraphicsData}">
<ListBox.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding Name}"></TextBlock>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</Grid>
我希望这对你有帮助