how to edit a WPF textbox which uses multibinding

2019-04-11 08:54发布

I have the following code.

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

How do I achieve that ?

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>

1条回答
太酷不给撩
2楼-- · 2019-04-11 09:47

StringFormat binding is oneway

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

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

   }
 }
查看更多
登录 后发表回答