Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>WPF's UI can contain objects of any type, even classes such as <code>Account</code>. If the WPF encounters an object in the UI it doesn't understand, it will render it by using a <code>TextBlock</code> containing the <code>.ToString()</code> of the object. </p> <p>In your case, the <code>ListBox.Item</code> is an <code>Account</code> object, so it is getting rendered with <code>Account.ToString()</code>, which returns the class name.</p> <p>There are many different ways of handling this. My preferred method is usually to use a <code>DataTemplate</code>. This creates an application-wide template that tells WPF how to draw an object of a specific type.</p> <pre><code>&lt;Window.Resources&gt; &lt;DataTemplate TargetType="{x:Type local:Account}"&gt; &lt;TextBlock Text="{Binding AccountName}" /&gt; &lt;/DataTemplate&gt; &lt;/Window.Resources&gt; </code></pre> <p>Another method is to overwrite the <code>ListBox.ItemTemplate</code> to specify what <code>ItemTemplate</code> to use for your <code>ListBox</code>. I would usually use this if I wanted to specify the template to use for this <code>ListBox</code> only</p> <pre><code>&lt;ListBox Name="MyAccounts"&gt; &lt;ListBox.ItemTemplate&gt; &lt;DataTemplate&gt; &lt;TextBlock Text="{Binding AccountName}" /&gt; &lt;/DataTemplate&gt; &lt;/ListBox.ItemTemplate&gt; &lt;/ListBox&gt; </code></pre> <p>If your template is simple, such as the one shown, you could also set the ListBox's <code>DisplayMemberPath</code> which makes the default template look like the one shown above, with the binding pointing to whatever you put in <code>DisplayMemberPath</code></p> <pre><code>&lt;ListBox Name="MyAccounts" DisplayMemberPath="AccountName" /&gt; </code></pre> <p>And of course, you could also overwrite your <code>Account</code> object's <code>ToString()</code> method to return <code>AccountName</code> instead of the default ClassName, however I wouldn't recommend it in this situation.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload