如何使用WPF绑定附加到c#中的对象列表

时间:2017-04-05 09:37:04

标签: c# wpf

型号:

public class Team
{
    public string KnownName { get; set; }     //player known name
    public bool IsActive { get; set; }      //player position
    public string Number { get; set; }    
}

WPF:

<DataTemplate x:Key="dtHomeSquad">
    <WrapPanel  >
        <TextBox x:Name="txtPath" Text="{Binding Path = Number, Mode=TwoWay}" ></TextBox>
        <TextBox x:Name="txtPath2" Text="{Binding Path = KnownName, Mode=TwoWay}" ></TextBox>
        <CheckBox x:Name="cbxInMatch" Click="AddOrRemoveFromMatch"IsChecked="{Binding IsActive}" />
    </WrapPanel>
</DataTemplate>

<ListBox x:Name="LstHomeSquadNames" HorizontalAlignment="Left" Height="423" Margin="4,10,0,0" VerticalAlignment="Top" Width="231"  ScrollViewer.VerticalScrollBarVisibility="Auto" FontSize="12"  ItemTemplate="{DynamicResource dtHomeSquad}" Grid.ColumnSpan="2"/>

C#:

private void AddOrRemoveFromMatch(object sender, RoutedEventArgs e)
{
    newlist = new List<Team>();

    foreach (var player in HomePlayersList)
    {      
        if(player.IsActive)
            newlist.Add(player);
    }
}

OnLoad我已使用项目源将对象列表绑定到我的列表框。当我选中复选框时,如果我取消选中是否从新列表中删除该对象(如果该对象不存在),则我会在列表框项中有一个复选框。

是否有一种方法可以添加新对象或使用唯一值删除而不是每次创建新列表,例如,如果我必须按索引选择项目,我将使用列表框的索引。

3 个答案:

答案 0 :(得分:4)

您可以使用ObservableCollection代替List。它会通知视图是否更改了集合。您需要知道绑定使用INotifyPropertyChangedINotifyCollectionChanged接口进行通知和更新视图的基础。

答案 1 :(得分:1)

使用ObservableCollection<Team>代替List<Team>

答案 2 :(得分:0)

我添加了INotifyPropertyChanged为@ Connnell.O'Donnell和@DdarkSideE ...按预期工作。

型号:

public class Team : INotifyPropertyChanged
{
    public string KnownName { get; set; }     //player known name
    public string Number { get; set; }    
    public bool isActive;
    public bool IsActive
    {
        get { return IsActive; }
        set
        {
            if (value != isActive)
            {
                isActive = value;
                if(isActive)
                {
                    OnPropertyChanged("IsActive", true);
                }
                else
                {
                    OnPropertyChanged("IsActive", false);
                }

            }
        }
    }

}

protected void OnPropertyChanged(PropertyChangedEventArgs e)
{
    PropertyChangedEventHandler handler = PropertyChanged;
    if (handler != null)
        handler(this, e);
}

protected void OnPropertyChanged(string propertyName, bool state)
{
    OnPropertyChanged(new PropertyChangedEventArgs(propertyName));
    if(state)
    {
        WindowType1.HomeTeam.Add(this);
    }
    else
    {
        WindowType1.HomeTeam.Remove(WindowType1.HomeTeam.Where(i => i.Number == this.Number).Single());
    }
}

public event PropertyChangedEventHandler PropertyChanged;