如何编辑使用多重绑定和 string.format 的 WPF 文本框? [英] how to edit a WPF textbox which uses multibinding and string.format?

查看:46
本文介绍了如何编辑使用多重绑定和 string.format 的 WPF 文本框?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码.

这会以 H:M:S 格式显示数据.我想编辑这些值...并希望在视图模型中收到通知.

This displays data in following format H:M:S. I would like to edit these values...and wanted to be notified in viewmodel.

我如何做到这一点?

任何帮助将不胜感激.谢谢

Any help would be appreciated. Thanks

  <TextBox  DataContext="{Binding UpdateSourceTrigger=PropertyChanged}" >
                            <TextBox.Text>
                                <MultiBinding StringFormat=" {0}:{1}:{2}">
                                <Binding Path="ValueH" Mode="TwoWay" UpdateSourceTrigger="PropertyChanged" />
                                <Binding Path="ValueM" Mode="TwoWay" UpdateSourceTrigger="PropertyChanged"  />
                                <Binding Path="ValueS" Mode="TwoWay" UpdateSourceTrigger="PropertyChanged"  />
                            </MultiBinding>
                        </TextBox.Text>
                        </TextBox>

推荐答案

StringFormat binding is oneway

StringFormat binding is oneway

您需要做的是编写自己的多值转换器来实现 ConvertBack 方法.

What you will need to do is write your own multivalue converter that implements the ConvertBack method as well.

一个非常简单的转换器如下所示.您将需要添加错误检查,并且毫无疑问有更好的转换方式(可能使用正则表达式).另外,我不确定我的 DateTime 是否正确,但它为您提供了一个起点.

A very simplistic converter would be something like below. You will need to add error checking and there is no doubtly a better way to convert back (possibly with a regex). Plus I'm not sure that I got the DateTime bit right but it gives you a starting point.

public class TimeConverter : IMultiValueConverter
 {
   public object Convert(object[] values, Type targetType, object parameter, 
      System.Globalization.CultureInfo culture)
   {
     return string.Format("{0}:{1}:{2}",values[0],values[1],values[2]);       }

  public object[] ConvertBack(object value, Type[] targetTypes, object parameter, 
      System.Globalization.CultureInfo culture)
   {
     var date=DateTime.Parse((string)value);
     return new object[] { date.Hours,date.Minutes,date.Seconds };

   }
 }

这篇关于如何编辑使用多重绑定和 string.format 的 WPF 文本框?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆