使用gridview和WPF在listview中查找项目

时间:2017-02-14 14:18:22

标签: wpf

我正在寻找一种方法来了解我的listview是否包含值。以下是我的代码。

public class OnlineUserList
{
    public string Name { get; set; }
    public string Color { get; set; }
}

<ListView x:Name="lvOnlineUsers" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" SelectionMode="Single" SelectionChanged="lvOnlineUsers_SelectionChanged">
            <ListView.View>
                <GridView x:Name="lvOnlineUsersGridView" AllowsColumnReorder="False">
                    <GridViewColumn Header="Online Users" Block.TextAlignment="Center" TextOptions.TextFormattingMode="Display" TextBlock.FontWeight="Bold">
                        <GridViewColumn.CellTemplate>
                            <DataTemplate>
                                <TextBlock Name="tbOnlineUsersGridView" Text="{Binding Path=Name}" Foreground="{Binding Path=Color}" HorizontalAlignment="Center" VerticalAlignment="Center" TextOptions.TextFormattingMode="Display" Style="{StaticResource ResourceKey=lblLabel}" />
                            </DataTemplate>
                        </GridViewColumn.CellTemplate>
                    </GridViewColumn>
                </GridView>
            </ListView.View>
        </ListView>

public void AddUserToList(string username)
{
   lvOnlineUsers.Items.Add(new OnlineUserList { Name = username, Color = "Black" });
}

现在这就是问题

public void RemoveUserFromList(string username)
{
   if(lvOnlineUsers.Items.Contains(username))
       lvOnlineUsers.Items.Remove(username);
}

2 个答案:

答案 0 :(得分:1)

你应该学习MVVM。

同时,将项目放在ObservableCollection中,并将其分配给代码隐藏中listview的ItemsSource属性。此后,在我之后重复:永远不要触摸lvOnlineUsers.Items。永远,永远,永远。忘了它存在。你做的一切,都与ObservableCollection互动。搜索它,向其中添加项目,从中删除项目。用户界面将神奇而神秘地更新自己。

我将假设这是MainWindow。如果这是在不同的视图中,则构造函数将具有不同的名称。

public MainWindow()
{
    InitializeComponent();

    lvOnlineUsers.ItemsSource = _onlineUsers;
}

private ObservableCollection<OnlineUserList> _onlineUsers 
    = new ObservableCollection<OnlineUserList>();

public void AddUserToList(string username)
{
   _onlineUsers.Add(new OnlineUserList { Name = username, Color = "Black" });
}


public void RemoveUserFromList(string username)
{
    //  We don't search _onlineUsers for the string username, because 
    //  _onlineUsers doesn't contain strings. It contains your user class. 
    //  So instead, we look for the user class instance that has the name
    //  we want. 
    var found = _onlineUsers.FirstOrDefault(ou => ou.Name == username);

    if (found != null)
    {
        _onlineUsers.Remove(found);
    }
}

答案 1 :(得分:0)

在你研究MVVM之前,试试这个:

library(ggplot2)
samplelist <- list(a = data.frame(x = c(1:10), y=rnorm(10)),
                  b = data.frame(x=c(5:10), y = rnorm(6)),
                  c = data.frame(x=c(2:12), y=rnorm(11)))

p <- ggplot()
for (i in 1:3) p <- p + geom_line(data=samplelist[[i]], aes(x,y))
p