简体   繁体   中英

WPF/C# Bind Content from two Textboxes to a single label

I've been trying to bind two textboxes to a single label so the label always update depending on the content of two textboxes. However without luck. I managed to solve how to bind a single one.

by using

Content="{Binding Text,ElementName=PersonName,UpdateSourceTrigger=PropertyChanged}"

So it looks like this

<UserControl x:Class="FitTracker.CreateTrackItem"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
             xmlns:local="clr-namespace:FitTracker"
             mc:Ignorable="d" 
             d:DesignHeight="300" d:DesignWidth="300">
  <Grid>    
    <TextBox Name="PersonName" HorizontalAlignment="Left" Height="23" Margin="10,77,0,0" TextWrapping="Wrap" Text="Name" VerticalAlignment="Top" Width="280" />
    <TextBox Name="PersonLevel" HorizontalAlignment="Left" Height="23" Margin="10,105,0,0" TextWrapping="Wrap" Text="Level" VerticalAlignment="Top" Width="280"/>
    <Label Name="TrackDetails" Content="{Binding Text,ElementName=PersonName,UpdateSourceTrigger=PropertyChanged}" HorizontalAlignment="Left" Margin="10,133,0,0" VerticalAlignment="Top" Width="280" FontWeight="Bold" Background="#00000000" Foreground="White" />
  </Grid>
</UserControl>

However I cannot do it with two text boxes. any ideas or guides that could help me on the right path.

I've been searching around for some hours now.

Use a MultiBinding:

<TextBox x:Name="PersonName"/>
<TextBox x:Name="PersonLevel"/>
<TextBlock>
    <TextBlock.Text>
        <MultiBinding StringFormat="Name: {0}, Level: {1}">
            <Binding Path="Text" ElementName="PersonName"/>
            <Binding Path="Text" ElementName="PersonLevel"/>
        </MultiBinding>
    </TextBlock.Text>
</TextBlock>

You can use a TextBlock with multiple Run elements:

<TextBox x:Name="PersonName"/>
<TextBox x:Name="PersonLevel"/>
<TextBlock>
    <TextBlock.Inlines>
        <Run Text="{Binding Text, ElementName=PersonName}"/>
        <Run Text="{Binding Text, ElementName=PersonLevel}"/>
    </TextBlock.Inlines>
<TextBlock>

You can also declare a new property, for example

public string JoinedProps {get {return PersonName+ PersonLevel;}}

Do not forget to notify JoinedProps' property change on both of the PersonName and PersonLevel fields

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM