简体   繁体   English

使用列表框进行数据绑定

[英]Databinding with a listbox

I have a bit of code that reads a json response from an HTTP server, it then parses this and inserts the data into a ListBox control.我有一段代码从 HTTP 服务器读取 json 响应,然后解析它并将数据插入到ListBox控件中。

The event I fire off when the download is complete is the following:下载完成后我触发的事件如下:

 void webClient_OpenReadCompleted(object sender, OpenReadCompletedEventArgs e)
 {
     DataContractJsonSerializer ser = null;

     try
     {
         ser =
        new DataContractJsonSerializer(typeof(ObservableCollection<UserLeaderboards>));

         ObservableCollection<UserLeaderboards> users =
            ser.ReadObject(e.Result) as ObservableCollection<UserLeaderboards>;

         foreach (UserLeaderboards em in users)
         {
             int Fid = em.id;
             string Fusername = em.username;
             int Fscore = em.score;
             lstbLeaders.Items.Add(Fid + Fusername + Fscore);
         }
     }
     catch (Exception ex)
     {
         MessageBox.Show(ex.Message);
     }
 }

Now, when I do the items.add I presume it's just joining up the 3 variables and adding it to one column in the ListBox .现在,当我执行items.add时,我认为它只是将 3 个变量连接起来并将其添加到ListBox的一列中。 This works fine and I see all 3 items joined up and displayed.这工作正常,我看到所有 3 个项目都连接并显示。

I want to separate this and make it look a bit nicer so I've created some XAML to try and bind the variables to textblocks.我想把它分开,让它看起来更好一点,所以我创建了一些XAML来尝试将变量绑定到文本块。 The following is just binding the username.以下只是绑定用户名。 I also have a public class that get/sets all 3 variables.我还有一个公共 class 可以获取/设置所有 3 个变量。

<ListBox Height="346" HorizontalAlignment="Left" Margin="5,221,0,0" 
         Name="lstbLeaders" VerticalAlignment="Top" Width="446">
   <DataTemplate>                            
       <TextBlock Text="{Binding Source=Fusername}" />                           
   </DataTemplate>
</ListBox>

When running the above I get nothing displayed at all.运行上述内容时,我什么也没有显示。 I have a feeling it's something simple?我有一种感觉,这很简单?

Thanks.谢谢。

To display a simple string your xaml should look like this:要显示一个简单的字符串,您的 xaml 应该如下所示:

<ListBox Height="346" HorizontalAlignment="Left" Margin="5,221,0,0" 
         Name="lstbLeaders" VerticalAlignment="Top" Width="446">
    <ListBox.ItemTemplate>
        <DataTemplate>                            
           <TextBlock Text="{Binding}" />                           
        </DataTemplate>
    <ListBox.ItemTemplate>
</ListBox>

and you have to provide an object instead of a simple string if you want to split the properties to make it look nicer.如果要拆分属性以使其看起来更好,则必须提供 object 而不是简单的字符串。 If you just add Fid + Fusername + Fscore you will end up with a plain string.如果你只是添加Fid + Fusername + Fscore你最终会得到一个纯字符串。

<ListBox Height="346" HorizontalAlignment="Left" Margin="5,221,0,0" 
         Name="lstbLeaders" VerticalAlignment="Top" Width="446">
    <ListBox.ItemTemplate>
        <DataTemplate>                            
           <StackPanel Orientation="Horizontal">
               <TextBlock Text="{Binding Id}" />                           
               <TextBlock Text="{Binding Name}" />                           
               <TextBlock Text="{Binding Score}" />                           
           </StackPanel> 
        </DataTemplate>
    <ListBox.ItemTemplate>
</ListBox>

You will need a view class:您将需要查看 class:

public class UserView
{
    public string Id {get;set;}
    public string Name {get;set;}
    public int Score {get;set;}
}

in your code behind:在你后面的代码中:

var usersList = new List<UserView>();

foreach (UserLeaderboards em in users)
{
    int Fid = em.id;
    string Fusername = em.username;
    int Fscore = em.score;
    usersList.Add(new UserView { Id = Fid, Name = Fusername, Score = Fscore} );
}

lstbLeaders.ItemsSource = usersList;

Further notes:补充说明:

  • Why not bind the ObservableCollection<UserLeaderboards> direcectly to the list box?为什么不将ObservableCollection<UserLeaderboards>直接绑定到列表框?

If there is no reason to convert to an other type skip the foreach part of the code and simply set lstbLeaders.ItemsSource = users;如果没有理由转换为其他类型,请跳过代码的foreach部分并简单地设置lstbLeaders.ItemsSource = users; . .

void webClient_OpenReadCompleted(object sender, OpenReadCompletedEventArgs e)
{
    try
    {
         var ser = new DataContractJsonSerializer(
                    typeof(ObservableCollection<UserLeaderboards>));

         var users = ser.ReadObject(e.Result)
                         as ObservableCollection<UserLeaderboards>;

         lstbLeaders.ItemsSource = users;
     }
     catch (Exception ex)
     {
         MessageBox.Show(ex.Message);
     }
}
  • Take look at the MVVM pattern.看看 MVVM 模式。 If you want to work with XAML you should know about this.如果你想使用 XAML 你应该知道这一点。 It simplifies your work and creates cleaner code.它简化了您的工作并创建了更简洁的代码。

  • If you want to add edit functionality or data can change you may need to implement INotifyPropertyChanged on the View class.如果您想添加编辑功能或数据可以更改,您可能需要在视图 class 上实现INotifyPropertyChanged

  • You can use type inference which especially helps when working with cumbersome class names.您可以使用类型推断,这在处理繁琐的 class 名称时尤其有用。 var list = new ObservableCollection<SomeLongTypeName>() saves much typing and screen estate. var list = new ObservableCollection<SomeLongTypeName>()节省了大量的打字和屏幕空间。

  • Hungarian notation makes me cringe;)匈牙利符号让我畏缩;)

I think you missed the ItemTemplate.我认为您错过了 ItemTemplate。 Try this尝试这个

<ListBox Height="346" HorizontalAlignment="Left" Margin="5,221,0,0" Name="lstbLeaders"         VerticalAlignment="Top" Width="446">
    <ListBox.ItemTemplate>
        <DataTemplate>                                  
            <TextBlock Text="{Binding Source=Fusername}" />                      
        </DataTemplate>
    </ListBox.ItemTemplate>
</ListBox> 

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

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