Reputation: 233
I have a class Employee in a WPF Project:
class Employee
{
public int ID { get; set; }
public string Name { get; set; }
}
And I am creating an instance of it emp2
in my XAML file:
<Window x:Class="WpfApplication1.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:WpfApplication1"
Title="MainWindow" Height="350" Width="525">
<Window.Resources>
<local:Employee x:Key="emp2" ID="20" Name="Second Employee "></local:Employee>
</Window.Resources>
<StackPanel>
<Label x:Name="lblEmpInfo2" FontSize="18" Margin="20" Content="{StaticResource emp2}"></Label>
</StackPanel>
</Window>
However this only displays the datatype of emp2
i.e. WpfApplication1.Employee
. How do I display the ID and Name of emp2
Upvotes: 1
Views: 1962
Reputation: 181
You have multiple options:
Use DataTemplates (MatthiasG's answer)
Quick and dirty: Implement ToString() in class Employee, simple but not very flexible.
Use StaticResource as Binding Source:
<StackPanel>
<Label Content="{Binding ID, Source={StaticResource emp2}}"></Label>
<Label Content="{Binding Name, Source={StaticResource emp2}}"></Label>
</StackPanel>
Upvotes: 0
Reputation: 1553
Your binding's just a wee bit off:
<Label x:Name="lblEmpInfo2" FontSize="18" Margin="20" Content="{Binding Source={StaticResource emp2}, Path=ID}"></Label>
Upvotes: 1
Reputation: 10764
Like this:
<Label x:Name="lblEmpInfo2" FontSize="18" Margin="20" Content="{Binding Path=Name, Source={StaticResource emp2}}"></Label>
Or implement the ToString
method override of the Employee
class
public override string ToString()
{
return string.Format("{0} {1}", Id, Name);
}
Upvotes: 2
Reputation: 4532
WPF uses the concept of DataTemplates
to give you the possibility to decide how data objects should be presented. Therefore you could define a DataTemplate
for the class Employee
and then use a ContentControl
which uses the instance of the Employee
class as its Content
. The DataTemplate
could contain controls to show the values.
<Window.Resources>
<local:Employee x:Key="emp2" ID="20" Name="Second Employee "></local:Employee>
<DataTemplate DataType={x:Type local:Employee}">
<StackPanel>
<TextBlock Text={Binding ID} />
<TextBlock Text={Binding Name} />
</StackPanel>
</DataTemplate>
</Window.Resources>
<StackPanel>
<ContentControl Content="{StaticResource emp2}" />
</StackPanel>
Upvotes: 2