繁体   English   中英

如何绑定从集合WPF继承的类

[英]How to bind class that inherit from collection wpf

我是WPF的新手,我在使用简单的ListBox绑定时遇到了麻烦。

是这种情况,我有两个说法

public class Child, ImplementedPropertyChanged
{
    private string _name;
    public string Name 
    { 
        get => _name;
        set
        {
            _name = value;
            OnPropertyChanged();
        }
    }
}

public class ChildCollection : IObservableCollection<Child>
{
    new public void Add(Child child)
    {
        //some logic
        base.Add(child);
    }
}

我正在尝试将其绑定到XAML

<Window x:Class="GeneradorDeCarpetaPlanos.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:GeneradorDeCarpetaPlanos"
        xmlns:VM="clr-namespace:GeneradorDeCarpetaPlanos.ViewModel"
        mc:Ignorable="d"
        Title="MainWindow" Height="450" Width="800">
        <Window.DataContext>
            <VM:ChildCollection></VM:ChildCollection>
        </Window.DataContext>

    <StackPanel>

        <ListBox ItemsSource="{Binding}">
            <ListBoxItem>
                <TextBlock Text="{Binding Path=Name}"></TextBlock>
            </ListBoxItem>
        </ListBox>       

    </StackPanel>
</Window>

并在后面的代码中

ChildCollection childs = null;
    public MainWindow()
    {
        childs = new ChildCollection();            
        InitializeComponent();
        DataContext = childs;
    }

我尝试将Count属性绑定到一个简单的TextBlock ,这显示了Count但未使用ChildCollection对象更新

我应该如何绑定它?

谢谢!

问题是您将ListBoxItem显式添加到ListBox。

您可能想改为定义ItemTemplate

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

您还应该考虑使用ObservableCollection而不是创建自己的集合类:

private readonly ObservableCollection<Child> children = new ObservableCollection<Child>();

public MainWindow()
{
    InitializeComponent();
    DataContext = children;
}

我认为问题出在可可收集的不恰当定义中。 无论如何,对于学习场景,请尝试使用标准的预定义System.ObservableCollection <>。 在那个小实验中,还必须初始化集合(不是nbe null)。

因此,根据您的情况,请尝试以下操作:

ObservablledCollection<Child> childs = new ObservableCollection<Child>;

public MainWindow()
{
    InitializeComponent();
    DataContext = childs;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM