Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multi binding in UWP

Tags:

xaml

uwp

uwp-xaml

I want to display a textblock with latitude and longditude. In my model, the lat and lng are two variables, so I need to combine them, preferably with stringformat as this answer suggests. Unfortunately it doesn't seem like multi binding is supported in UWP applications.

That leaves me with a couple of options.

  1. Create two text blocks that are bound to each variable and align them next to each other. I'm not sure if i need two extra textblocks to be able to display "lat" and "lng" in front of the values. And then an third label displaying "Position" in front of that again. This answer states that there is no stringformat property for Binding. A total of five textblocks is too much in my opinion.
    <RelativePanel>
        <TextBlock x:Name="EquipmentLatTextBox" 
                   Text="{Binding Equipment.lat}"/>
        <TextBlock x:Name="EquipmentLngTextBox"
                   Text="{Binding Equipment.lng}" 
                   RelativePanel.RightOf="EquipmentLatTextBox"/>
    </RelativePanel>
  1. Create a value converter. This also seems very unnecessary. I get the point of using converters to convert across data-types, but for concatinating strings there should be a buildt in property.

  2. Create a property in the view model that returns a string of the values as it should be displayed. This seems like the best option as the method is not in the model, but i still think that i should be able to do this in the xaml markup.

Is there a better way to do this?

like image 201
Kristoffer Berge Avatar asked Dec 18 '22 13:12

Kristoffer Berge


1 Answers

This can be solved by using runs. It's actually a lot easier to achieve this in UWP than with multi-binding in WPF. A TextBlock item can consist of several "runs" of text which can bind to different properties. The runs will behave like inline elements. Each run can have text directly between the tags, or as a text property. Each run-element can also have independent styling.

Documentation for the TextBlock class

For the example i provided in my question, i ended up formating it like this

<TextBlock x:Name="LocationTextBlock">
    <Run FontWeight="Bold">Location: </Run>
    <LineBreak />
    <Run>Lat: </Run>
    <Run Text="{x:Bind ViewModel.Equipment.Lat}"></Run>
    <Run> Lng: </Run>
    <Run Text="{x:Bind ViewModel.Equipment.Lng}"></Run>
</TextBlock>

The result looks like this

Location:
Lat: 00.000 Lng: 00.000

like image 177
Kristoffer Berge Avatar answered Dec 28 '22 09:12

Kristoffer Berge