Question

I have a Property which looks like this:

private int _wertungvalue;
public int WertungValue
{
    get { return _wertungvalue; }
    set
    {
        _wertungvalue = value;
        RaisePropertyChanged(() => WertungValue);
    }
}

It's binded to a TextBox

<TextBox Text="{Binding WertungValue, Mode=TwoWay}"/>

So the user can type in anything he wants (I don't want a numeric textbox!). The user types in '5' and the value of WertungValue is 5. If the user types in 'Test', a red border pops up and the value of WertungValue is still 5!

Now I also have a RelayCommand

RelayCommand(DeleteExecute,CanDelete);

In CanDelete, I check if the propery is an int

private bool CanDelete()
{
    int ot = 0;

    if (int.TryParse(WertungValue.ToString(),out ot) == false)
        return false;
    else
        return true;
}

so that the RelayCommand should only work, when the value is an integer. So this means when the user types in 'Test', RelayCommand should return false. The problem is that it will never return false, since the value of the property is always an integer, but in the View it's a string.

I don't want to make the property to type string or use UpdateSourceTrigger=PropertyChanged in my TextBox. I also don't want to make a numeric only TextBox... The user should be allowed to type in anything he wants, but the RelayCommand should only work when he types an integer.

Était-ce utile?

La solution

I don't think that this is possible with an int-property. When the Binding updates the property, it tries to convert the value to an integer, which causes an exception when the user enters 'Test', thus the value is never updated and stays 5.

I think you need two properties: One of type string, and one of type int (or maybe int?). The textbox is bound to the string property, and in the setter you can check if the value can be parsed and update the int property accordingly.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top