Binding showing type rather than value
Hey.
I've having some trouble with binding in XAML. I have a list of Player
objects. I would like this list to be bound to a ListBox and display the Name
of the Player
. At the moment, the List box is being filled with Red.Player
(i.e. the object type and namespace). My resource dictionary style looks like this:
<Style x:Key="PlayerListBox" TargetType="ListBoxItem">
<Setter Property="Background" Value="Transparent"/>
<Setter Property="BorderThickness" Value="0"/>
<Setter Property="BorderBrush" Value="Transparent"/>
<Setter Property="Padding" Value="0"/>
<Setter Property="HorizontalContentAlignment" Value="Left"/>
<Setter Property="VerticalContentAlignment" Value="Top"/>
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="ListBoxItem">
<Border x:Name="LayoutRoot" BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="{TemplateBinding BorderThickness}" Background="{TemplateBinding Background}" HorizontalAlignment="{TemplateBinding HorizontalAlignment}" VerticalAlignment="{TemplateBinding VerticalAlignment}" d:DesignWidth="231" d:DesignHeight="50">
<VisualStateManager.VisualStateGroups>
<VisualStateGroup x:Name="CommonStates">
<VisualState x:Name="Normal"/>
<VisualState x:Name="MouseOver"/>
<VisualState x:Name="Disabled">
<Storyboard>
<ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="Background" Storyboard.TargetName="LayoutRoot">
<DiscreteObjectKeyFrame KeyTime="0" Value="{StaticResource TransparentBrush}"/>
</ObjectAnimationUsingKeyFrames>
</Storyboard>
</VisualState>
</VisualStateGroup>
<VisualStateGroup x:Name="SelectionStates">
<VisualState x:Name="Unselected"/>
<VisualState x:Name="Selected"/>
</VisualStateGroup>
</VisualStateManager.VisualStateGroups>
<TextBlock TextWrapping="Wrap" Text="{Binding}" FontSize="29.333" TextAlignment="Center"/>
</Border>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
I guess the main part is this:
<TextBlock TextWrapping="Wrap" Text="{Binding}" FontSize="29.333" TextAlignment="Center"/开发者_开发技巧>
I tried using Text="{Binding Name}"
but then nothing shows up at all. I'm setting the ItemsSource
when the user selected a player:
PlayerList.ItemsSource = ListofPlayers;
Thanks for any help
Is Name a public property on the type you've bound to?
ie
public class Person
{
string name;
int age;
public string Name
{
get { return name; }
set { name = value; }
}
public int Age
{
get { return age; }
set { age = value; }
}
}
Sample project here demonstrating binding data to a listbox.
binding a Linq datasource to a listbox
Use de ListBox.ItemTemplate
property to set how the data is shown with respect to properties.
Eg.
<ListBox.DataTemplate> <DataTemplate> <TextBlock Text="{Binding Name}" /> </DataTemplate> </ListBox.DataTemplate>
If you want use {Binding}
without specifying a property, you can override ToString() to return the text you want to display.
精彩评论