【问题标题】:WPF/C# Bind Content from two Textboxes to a single labelWPF/C# 将两个文本框的内容绑定到一个标签
【发布时间】:2018-02-15 09:47:17
【问题描述】:

我一直在尝试将两个文本框绑定到一个标签,以便标签始终根据两个文本框的内容进行更新。然而没有运气。我设法解决了如何绑定一个。

通过使用

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

原来是这样的

<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>

但是我不能用两个文本框来做。任何可以帮助我走上正确道路的想法或指南。

我已经搜索了几个小时了。

【问题讨论】:

  • 请注意,设置UpdateSourceTrigger=PropertyChanged 在单向绑定中是没有意义的。它没有效果。
  • 还请注意,虽然之前已经提出过这个问题,但answers here 都没有显示如何使用 MultiBinding 的 StringFormat 而不是 Converter。

标签: c# wpf data-binding


【解决方案1】:

使用多重绑定:

<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>

【讨论】:

  • 我迟到了 1 分钟
  • 我确实读过这个。我还发现了人们在上面找到的一些链接,我真正的问题是我是 WPF 新手,我通常使用 web.xml 。但是如何让我的标签内容采用多绑定字符串?谢谢你帮助我
  • 使用文本块。这就是其他框架中通常的标签。如果要显示文本以外的内容(即图标),请仅使用标签。如果您真的想要使用标签,请为&lt;Label.Content&gt; 使用MultiBinding。但是请注意,您不能使用 StringFormat。你必须实现一个 IMultiValueConverter。
【解决方案2】:

您可以将 TextBlock 与多个 Run 元素一起使用:

<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>

【讨论】:

    【解决方案3】:

    你也可以声明一个新的属性,例如

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

    不要忘记在两个 PersonName 上通知 JoinedProps 的属性更改 和 PersonLevel 字段

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-04-17
      • 1970-01-01
      • 2013-03-21
      • 1970-01-01
      • 2011-10-13
      • 1970-01-01
      • 2010-10-20
      相关资源
      最近更新 更多