如何显示在XAML中初始化的类对象的类属性

时间:2015-07-27 14:36:55

标签: wpf xaml

我在WPF项目中有一个类Employee:

class Employee
{
    public int ID { get; set; }
    public string Name { get; set; }
}

我正在我的XAML文件中创建一个emp2的实例:

<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>

但是,这仅显示emp2的数据类型,即WpfApplication1.Employee。如何显示emp2

的ID和名称

4 个答案:

答案 0 :(得分:2)

WPF使用DataTemplates的概念为您提供决定数据对象应如何呈现的可能性。因此,您可以为类DataTemplate定义Employee,然后使用ContentControl使用Employee类的实例作为其ContentDataTemplate可以包含显示值的控件。

<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>

答案 1 :(得分:2)

像这样:

<Label x:Name="lblEmpInfo2" FontSize="18" Margin="20" Content="{Binding Path=Name, Source={StaticResource emp2}}"></Label>

或实施ToString

Employee方法覆盖
public override string ToString()
{
    return string.Format("{0} {1}", Id, Name);
}

答案 2 :(得分:1)

你的约束只是一点点关闭:

<Label x:Name="lblEmpInfo2" FontSize="18" Margin="20" Content="{Binding Source={StaticResource emp2}, Path=ID}"></Label>

答案 3 :(得分:0)

您有多种选择:

  1. 使用DataTemplates(MatthiasG的回答)

  2. 快速而又脏:在Employee类中实现ToString(),简单但不是很灵活。

  3. 使用StaticResource作为绑定源:

    Array
    (
        [0] => 1
        [1] => 2
        [2] => 2
    )
    Array 
    (
        [0] => 1
        [1] => 2
        [2] => 1
    )
    Array
    (
        [0] => 2
        [1] => 1
        [2] => 1
    )
    Array
    (
        [0] => 3
        [1] => 3
        [2] => 1
    )
    Array
    (
        [0] => 3
        [1] => 3
        [2] => 3
    )
    Array
    (
        [0] => 3
        [1] => 3
        [2] => 2
    )
    Array
    (
        [0] => 4
        [1] => 2
        [2] => 2
    )
    Array
    (
        [0] => 4
        [1] => 2
        [2] => 1
    )