0

I created Coverter which works as number only validation for TextBoxes. Everything is fine, i use it in few places, but there is one place where it just doesn't work, i debbuged it and it works at the begining, like it was mode OneTime.

Converter:

        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        var val = value.ToString();
        return (string.IsNullOrEmpty(val) ? "" : ( (val.Substring(val.Length - 1).Equals(",") && val.Count(x => x == ',') < 2) || char.IsDigit(System.Convert.ToChar(val.Substring(val.Length - 1))) ? val : val.Substring(0,val.Length-1)));
    }

And i don't know if does matters, but one time it is used in Window, and second time in Page, and it doesn't work in Page. Page:

                <TextBox Name="PeselTextBox"
                Margin="2,5"
                Width="70"
                VerticalAlignment="Center"
                Text="{Binding ElementName=PeselTextBox,
                               Path=Text,
                               Mode=OneWay,
                               UpdateSourceTrigger=PropertyChanged,
                               Converter={StaticResource NumberValidationConverter}}"/>

And in Window it is same. Tried to search for solution , but i just don't understand this error.

Zeronader
  • 95
  • 7
  • as a side note: your validation won't work in at least 2 cases: ***copy & paste*** and ***move caret around before actually typing*** - it is not assumed to be always kept at the end of the TextBox. I've tried your code in Window and the Binding works (not just once), so it's strange to hear that it does not work for Page. – King King Oct 10 '15 at 00:32
  • The `Binding` is referring to the defining element itself. Why? – Sandesh Oct 10 '15 at 05:19
  • @KingKing It actually works in other Page, only not in this one. – Zeronader Oct 10 '15 at 22:29

1 Answers1

0

First off, don't use converters for validation. That's not what they are intended for or good at. If you need validation, look at Using IDataErrorInfo in M-V-VM

That said, you are using mode OneWay. That means that the only thing the binding does is reflect changes in the view model (via PropertyChanged) which shouldn't need to be validated anyways! If you want to convert before applying changes to the view model, use the ConvertBack method and mode TwoWay or OneWayToSource.

Community
  • 1
  • 1
BradleyDotNET
  • 60,462
  • 10
  • 96
  • 117
  • I know it should be done with IDataError but i'm still learning MVVM and this project is still in code behind , so don't have any viewmodel here. But i wanted to make some validation nicer than textChanged event – Zeronader Oct 10 '15 at 00:14
  • @Zeronader well, you are clearly using your code-behind as a view model then (or your bindings wouldn't work at all). Regardless, best to start good practices now! Having a proper view model will help make future work a lot easier. – BradleyDotNET Oct 10 '15 at 00:15