如何让多绑定在XAML ListBox中工作?

时间:2009-02-23 13:51:02

标签: xaml listbox

以下显示了ListBox中的3x“MultiTest.Model.Customers”(每个记录应显示一个)。

我需要更改哪些内容才能输出字段的内容

<Window.Resources>
    <Style TargetType="{x:Type ListBoxItem}">
        <Setter Property="ContentTemplate" >
            <Setter.Value>
                <MultiBinding StringFormat="{}{1}, {0} ">
                    <Binding Path="FirstName" />
                    <Binding Path="LastName"/>
                </MultiBinding>
            </Setter.Value>
        </Setter>
    </Style>
</Window.Resources>
<Grid>
    <ListBox x:Name="theCustomers"/>
</Grid>
代码隐藏中的

绑定与ADO.NET实体框架:

MainEntities db = new MainEntities();
var customers = from c in db.CustomersSet
                select c;
theCustomers.ItemsSource = customers;

解答:

谢谢,史蒂夫,这是我的Window.Resources格式的答案:

<Window.Resources>
    <Style TargetType="{x:Type ListBoxItem}">
        <Setter Property="ContentTemplate" >
            <Setter.Value>
                <DataTemplate>
                    <StackPanel Orientation="Horizontal">
                        <TextBlock>
                            <TextBlock.Text>
                                <MultiBinding  StringFormat="{}{1}, {0} ({2})">
                                    <Binding Path="FirstName"/>
                                    <Binding Path="LastName"/>
                                    <Binding Path="ID"/>
                                </MultiBinding>
                            </TextBlock.Text>
                        </TextBlock>
                    </StackPanel>
                </DataTemplate>
            </Setter.Value>
        </Setter>
    </Style>
</Window.Resources>
<Grid>
    <ListBox x:Name="theCustomers"/>
</Grid>

2 个答案:

答案 0 :(得分:2)

如果您特别想使用MultiBinding,您应该能够将DataTemplate与StringFormat一起使用..类似于:

<ListBox.ItemTemplate>
    <DataTemplate>
        <StackPanel Orientation="Horizontal">
            <TextBlock>
                <TextBlock.Text>
                    <MultiBinding  StringFormat="{}{1}, {0}">
                        <Binding Path="FirstName"/>
                        <Binding Path="LastName"/>
                    </MultiBinding>
                </TextBlock.Text>
            </TextBlock>
       </StackPanel>
    </DataTemplate>
</ListBox.ItemTemplate>

或者对于更复杂的东西,你可以使用ValueConverter(或多重绑定变体)。

答案 1 :(得分:1)

我之前从未使用过MultiBinding。但是,我使用了DataTemplates:

<ListBox.ItemTemplate>
    <DataTemplate>
        <StackPanel Orientation="Horizontal">
            <TextBlock Text="{Binding Name}"></TextBlock>
            <TextBlock Text=" - "/>
            <TextBlock Text="{Binding Email}" Margin="5,0"></TextBlock>
        </StackPanel>
    </DataTemplate>
</ListBox.ItemTemplate>

希望这有帮助!