【问题标题】:How to bind 2 textboxes to one property?如何将 2 个文本框绑定到一个属性?
【发布时间】:2014-02-15 17:38:14
【问题描述】:

我有一个属性PhoneNumber,在 UI 中,我有 2 个文本框,一个是前缀,另一个是后缀,如何将其绑定到属性? (DataContext 内的属性)。

<TextBox Grid.Column="0" MaxLength="3" /> //Prefix
<TextBlock Grid.Column="1" Text="-" />
<TextBox Grid.Column="2" /> //Postfix

我看到它工作的唯一方法是使用 textbox1.Text + textbox2.Text 后面的代码...有更好的方法吗?

提前致谢:)

【问题讨论】:

  • @Blam 我想你不明白这个问题。问题不是如何绑定,而是如何将两个文本框绑定到一个属性中?它不是常规绑定,也不是 MultiBinding。
  • @Blam 你看过我的帖子了吗?我也写了我尝试过的。
  • 我看到和尝试的方式不是一回事。我明白这个问题。 textbox1.Text + textbox2.Text 没有绑定,这就是我评论绑定链接的原因。

标签: c# xaml binding


【解决方案1】:

只需在数据上下文中使用另外两个属性

代码未经过编译或测试

public string PhoneNumber { get; set; }
public string Prefix
{
    get
    {
        return PhoneNumber.Substring(0, 3);
    }
    set
    {
        // replace the first three chars of PhoneNumber
        PhoneNumber = value + PhoneNumber.Substring(3);
    }
}
public string Postfix
{
    get
    {
        return PhoneNumber.Substring(3);
    }
    set
    { 
        // replace the  chars of starting from index 3 of PhoneNumber
        PhoneNumber =  PhoneNumber.Substring(0, 3) + value;
    }
}

【讨论】:

  • +1,你是对的 - 与我使用转换器的解决方案相比,它会更容易。
  • @Romasz-我缺少现在添加的 setter 部分
  • 看起来不错。 OP 只需正确解析他的电话号码(带/不带分号或其他格式)。
【解决方案2】:

我认为你可以为此目的使用 Converter,单向的示例可能如下所示:

在此我的号码是string 000-000000,但您当然可以更改它。

在 XAML 中:

<Window.Resources>
    <conv:PostixConverter x:Key="PostfixConv" xmlns:conv="clr-namespace:Example.Converters"/>
    <conv:PrefixConverter x:Key="PrefixConv" xmlns:conv="clr-namespace:Example.Converters"/>
</Window.Resources>
<StackPanel>     
    <TextBox  MaxLength="3" Text="{Binding Number, Converter={StaticResource PrefixConv}}"/> 
    <TextBlock  Text="-" />
    <TextBox Text="{Binding Number, Converter={StaticResource PostfixConv}}"/>
</StackPanel>

在后面的代码中:

namespace Example.Converters
{
  public class PrefixConverter : IValueConverter
  {
    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        if (value == null) return null;
        else return ((string)value).Substring(0, 3);
    }

    public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        throw new NotImplementedException();
    }
  }

  public class PostixConverter : IValueConverter
  {
      public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
      {
        if (value == null) return null;
        else return ((string)value).Substring(4);
      }

      public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
      {
        throw new NotImplementedException();
      }
  }
}

【讨论】:

    猜你喜欢
    • 2013-03-21
    • 1970-01-01
    • 1970-01-01
    • 2023-04-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-11-14
    • 1970-01-01
    相关资源
    最近更新 更多