Bind Textblock text to 2 different properties

我怕爱的太早我们不能终老 提交于 2020-01-24 20:57:57

问题


I have a binded treeview that displays one of the properties (namely, the displayname) of the treeviewitem (which are custom viewmodel's of an object).

Here is the associated xaml:

<local:ExtendedTreeView.ItemTemplate>
                    <HierarchicalDataTemplate ItemsSource="{Binding SubOrganLocations}">
                        <TextBlock Text="{Binding OrganDisplayName}" >
                        </TextBlock>
                    </HierarchicalDataTemplate>
                </local:ExtendedTreeView.ItemTemplate>

What I want is to be able to display another property next to the display name in parenthesis.

so instead of the treeview looking like this:

Root
-sub node1
--subsub node1
-sub node2

I want it to look like this:

Root (Type1)
    -sub node1 (Type2)
    --subsub node1 (Type 3)
    -sub node2 (Type 1)

How can I accomplish this? Using multi-binding?


回答1:


Try this:

<TextBlock>
   <TextBlock.Text>
      <MultiBinding StringFormat="{}{0} ({1})">
          <Binding Path="{YourBindingHere}" />
          <Binding Path="{YourBindingHere}" />
      </MultiBinding>
   </TextBlock.Text>
</TextBlock>



回答2:


You could just use multiple text blocks

<local:ExtendedTreeView.ItemTemplate>
    <HierarchicalDataTemplate ItemsSource="{Binding SubOrganLocations}">
        <Grid>
            <Grid.ColumnDefinitions>
                <ColumnDefinition />
                <ColumnDefinition />
            </Grid.ColumnDefinitions>
            <TextBlock Text="{Binding OrganDisplayName}" />
            <TextBlock Grid.Column="1" Text="{Binding TypeName}" />
        </Grid>
    </HierarchicalDataTemplate>
</local:ExtendedTreeView.ItemTemplate>

Or you could add a property to your view model which calculate the full name internally and just bind to that.




回答3:


Or use <Run/>:

<TextBlock>
  <Run Text="{Binding OrganDisplayName}"/>
  <Run Text=" ("/>
  <Run Text="{Binding TypeName}"/>
  <Run Text=")"/>
</TextBlock>


来源:https://stackoverflow.com/questions/5407292/bind-textblock-text-to-2-different-properties

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!