我有一个如下所示的属性:
private int _wertungvalue;
public int WertungValue
{
get { return _wertungvalue; }
set
{
_wertungvalue = value;
RaisePropertyChanged(() => WertungValue);
}
}
它被绑定到一个TextBox
<TextBox Text="{Binding WertungValue, Mode=TwoWay}"/>
这样用户就可以输入任何他想要的东西(我不想要数字文本框!)。用户输入' 5‘,测试的值是5。如果用户输入的是’WertungValue‘,则会弹出一个红色边框,而测试的值仍然是5!
现在我也有了一个RelayCommand
RelayCommand(DeleteExecute,CanDelete);
在CanDelete中,我检查属性是否为整型
private bool CanDelete()
{
int ot = 0;
if (int.TryParse(WertungValue.ToString(),out ot) == false)
return false;
else
return true;
}
因此,只有当值为整数时,RelayCommand才能工作。所以这意味着当用户输入'Test‘时,RelayCommand应该返回false。问题是它永远不会返回false,因为属性的值总是一个整数,但在视图中它是一个字符串。
我不想在TextBox中将该属性设置为string类型或使用UpdateSourceTrigger=PropertyChanged。我也不想做一个只有数字的TextBox...应该允许用户键入他想要的任何内容,但是RelayCommand应该只在他键入整数时才起作用。
发布于 2013-06-12 12:23:23
我不认为使用int-property可以做到这一点。当绑定更新属性时,它会尝试将值转换为整数,这会在用户输入'Test‘时导致异常,因此该值永远不会更新,并保持为5。
我认为您需要两个属性:一个是string类型,另一个是int (或者int?)类型。textbox被绑定到string属性,在setter中,您可以检查该值是否可以解析,并相应地更新int属性。
https://stackoverflow.com/questions/17062984
复制