wpf pro pls
wpf pro pls

Reputation: 87

Binding to 2 string elements?

Is it possible in WPF to bind to 2 elements?

For example I'd like to display something like myserver.com:80 in a textbox. So to do this I'd like to bind to both a Host field then add a ":" then bind to a port field in my object all for the same label content.

Upvotes: 2

Views: 358

Answers (1)

Kent Boogaart
Kent Boogaart

Reputation: 178630

In WPF 4/3.5SP1 you can use a MultiBinding in conjunction with StringFormat:

<TextBlock>
    <TextBlock.Text>
        <MultiBinding StringFormat="{0}:{1}">
            <Binding Path="Host"/>
            <Binding Path="Port"/>
        </MultiBinding>
    </TextBlock.Text>
</TextBlock>

Prior to WPF 4 you can still use a MultiBinding but would need to write your own converter instead.

An alternative to both these approaches is do MVVM and expose a property that does the concatenation for the view, then the view just binds directly to that property.

Upvotes: 5

Related Questions