在运行时更改ObservableCollection以进行绑定

时间:2014-07-03 12:31:12

标签: c# wpf data-binding observablecollection

我正在为我的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(这是同一个类只是不同的列表)。我该怎么做?

1 个答案:

答案 0 :(得分:2)

您可以在集合中添加或删除项目,如下所示

        var dresource = this.Resources["GraphicsData"] as GraphicsList;
        dresource.Add(new Graphics() { Name = "New Entry" });

但是使用StaticResource,您无法将新的Collection分配给ResourceDictionary中的一个。

理想情况下,如果要分配全新的集合,则应使用ViewModel并绑定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));
    }
}

和你的Xaml

    <Grid>
    <ListBox ItemsSource="{Binding GraphicsData}">
        <ListBox.ItemTemplate>
            <DataTemplate>
                <TextBlock Text="{Binding Name}"></TextBlock>
            </DataTemplate>
        </ListBox.ItemTemplate>
    </ListBox>
</Grid>

我希望这会有所帮助