开发者

WPF listview display converter

开发者 https://www.devze.com 2023-03-18 16:45 出处:网络
I have a collection of objects that derive from a Person class and I want to bind this collection to the ItemsSource of a ListView.

I have a collection of objects that derive from a Person class and I want to bind this collection to the ItemsSource of a ListView.

I want to specify a string to display in the ListView Items. This string will be a composite of properties found on the derived classes.

I also want to bind the SelectedItem of the ListView to a property of type Person in my view model.

As far as I see it I need a string converter for my display string but I'm unsure how to bind to the items within the ItemsSource to generate the compo开发者_如何学Gosite display string.

Can anyone give me a pointer?

Thanks.


You can either overwrite the ToString() method of your derived classes to return your composite display string, or you can create a Converter like you are suggesting and pass it the entire Item. The converter would then check that the item is of a specified type, and if so compose a string of whatever properties you want.


you dont need the StringConverter, you need DataTemplate

using DataTemplate, you can choose how you would like to display you data as an item in your listBox.


If you could consider your derived class a ViewModel then you could just add a property to that class and then display it in the ListView ItemTemplate. Or like Rachel suggested override your ToString Method and then in your display binding simply write "{Binding}" which will force WPF to call the ToString method

e.g.

public class DerivedPerson : Person
{
  public string DisplayString 
  {
    get 
    {
      return string.Format("{0} {1}",FirstName,LastName);
    }
  }  
}

And you xaml:

<ListView ItemsSource="{Binding PersonList}" SelectedItem="{Binding SelectedPerson}">
  <ListView.ItemTemplate>
    <DataTemplate>
      <TextBlock Text={Binding DisplayString}"/>
    </DataTemplate>
  </ListView.ItemTemplate>
</ListView>
0

精彩评论

暂无评论...
验证码 换一张
取 消