使用 ReactiveUI 绑定 TextBox 并保持货币格式
Bind TextBox with ReactiveUI and maintain Currency Format
有没有办法将 decimal
绑定到 WPF 文本框并指定 StringFormat
(在本例中为货币)?我已经尝试在视图模型中使用 属性 来执行此操作,但是在 TextBox 中进行编辑变得有点古怪,因为它会在每次击键后尝试应用格式:
public string Moneys
{
get
{
return string.Format("{0:C}", Model.Moneys);
}
set
{
if ( decimal.TryParse(value, NumberStyles.Currency, null, out decimal decimalValue) )
{
Model.Moneys = decimalValue;
}
}
}
我尝试设置 DataContext
并改为使用 Xaml 数据绑定。 Xaml:
<TextBox Text="{Binding Path=Moneys, StringFormat=C0}" />
后面的代码:
this.WhenAnyValue(x => x.ViewModel.Model)
.Subscribe(x =>
{
DataContext = x;
});
但是,在更改 DataContext
之后,{Binding}
并没有像我预期的那样更改。
有没有办法使用 this.Bind
并指定 StringFormat
?对我来说,那将是理想的解决方案
更新
在设置 DataContext
的情况下,我意识到我应该将它分配给 ViewModel
,当 ViewModel.Model
发生变化时,模板会反映出它应该的变化.这是我更新的 xaml:
<TextBox Text="{Binding Path=Model.Moneys, StringFormat=C0}" />
不过,我还是想知道您是否可以在后面的代码中使用ReactiveUI
设置StringFormat
。
您可以使用内联绑定转换器,在后面的代码中进行绑定(您的文本框需要一个名称):
this.Bind(
ViewModel,
x => x.ViewModel.Model.Moneys,
x => x.nameOfTheTextbox,
x => ConvertToText(x),
x => ConvertToDec(x));
以及方法:
private string ConvertToText(decimal value)
{
return string.Format("{0:C}", value);
}
private decimal ConvertToDec(string value)
{
decimal result;
if (!decimal.TryParse(value, NumberStyles.Currency, null, out result))
{
result = 0;
}
return result
}
有没有办法将 decimal
绑定到 WPF 文本框并指定 StringFormat
(在本例中为货币)?我已经尝试在视图模型中使用 属性 来执行此操作,但是在 TextBox 中进行编辑变得有点古怪,因为它会在每次击键后尝试应用格式:
public string Moneys
{
get
{
return string.Format("{0:C}", Model.Moneys);
}
set
{
if ( decimal.TryParse(value, NumberStyles.Currency, null, out decimal decimalValue) )
{
Model.Moneys = decimalValue;
}
}
}
我尝试设置 DataContext
并改为使用 Xaml 数据绑定。 Xaml:
<TextBox Text="{Binding Path=Moneys, StringFormat=C0}" />
后面的代码:
this.WhenAnyValue(x => x.ViewModel.Model)
.Subscribe(x =>
{
DataContext = x;
});
但是,在更改 DataContext
之后,{Binding}
并没有像我预期的那样更改。
有没有办法使用 this.Bind
并指定 StringFormat
?对我来说,那将是理想的解决方案
更新
在设置 DataContext
的情况下,我意识到我应该将它分配给 ViewModel
,当 ViewModel.Model
发生变化时,模板会反映出它应该的变化.这是我更新的 xaml:
<TextBox Text="{Binding Path=Model.Moneys, StringFormat=C0}" />
不过,我还是想知道您是否可以在后面的代码中使用ReactiveUI
设置StringFormat
。
您可以使用内联绑定转换器,在后面的代码中进行绑定(您的文本框需要一个名称):
this.Bind(
ViewModel,
x => x.ViewModel.Model.Moneys,
x => x.nameOfTheTextbox,
x => ConvertToText(x),
x => ConvertToDec(x));
以及方法:
private string ConvertToText(decimal value)
{
return string.Format("{0:C}", value);
}
private decimal ConvertToDec(string value)
{
decimal result;
if (!decimal.TryParse(value, NumberStyles.Currency, null, out result))
{
result = 0;
}
return result
}