2015-09-01 49 views
1

我正在编写一个WPF程序在C#中,我试图找出一种方法来绑定两个文本框与十进制值。我有两个不同的文本框与两个不同的属性绑定。WPF - 文本框绑定十进制值

我想当用户更改“成本”时,“价格”会自动填充,当他更改“价格”时,成本也会自动填充。这产生像循环,我不想要。 而且我注意到,带有十进制值的文本框绑定不允许添加逗号和点字符'.'','

我该如何解决这两个问题?

这些文本框的XAML:

<TextBlock Grid.Row="0" Grid.Column="0" Text="Cost" Margin="5,5,0,0" /> 
<TextBox Grid.Row="1" Grid.Column="0" Text="{Binding Cost, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" /> 
<TextBlock Grid.Row="0" Grid.Column="1" Text="Price" Margin="5,5,0,0" /> 
<TextBox Grid.Row="1" Grid.Column="1" Text="{Binding Price ,Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" /> 

而且这是两个性质:

private decimal _cost; 
public decimal Cost 
{ 
    get { return _cost; } 
    set 
    { 
     if (_cost != value) 
     { 
      _cost = value; 
      NotifyOfPropertyChange("Cost"); 

      if (Cost > 0) 
      { 
       Price = Math.Round(_cost * ((decimal)1.50), 2); 
       NotifyOfPropertyChange("Price"); 
      } 

     } 
    } 
} 

private decimal _price; 
public decimal Price 
{ 
    get { return _price; } 
    set 
    { 
     if (_price != value) 
     { 
      _price = value; 
      NotifyOfPropertyChange("Price"); 

      if (Price > 0) 
      { 
       Cost = Math.Round(Price/(decimal)(1.55), 2); 
       NotifyOfPropertyChange("Cost"); 
      }      
     } 
    } 
} 

编辑解决方案 搜索在网络上,我找到了解决办法here只是需要添加StringFormat=0{0.0}。希望它能帮助别人。

回答

1

您可以使用backfields来设置值。看到流动

private decimal _cost; 
public decimal Cost 
{ 
    get { return _cost; } 
    set 
    { 
     if (_cost != value) 
     { 
      _cost = value; 
      NotifyOfPropertyChange("Cost"); 

      if (_cost > 0) 
      { 
       _price = Math.Round(_cost * ((decimal)1.50), 2); 
       NotifyOfPropertyChange("Price"); 
      } 

     } 
    } 
} 

private decimal _price; 
public decimal Price 
{ 
    get { return _price; } 
    set 
    { 
     if (_price != value) 
     { 
      _price = value; 
      NotifyOfPropertyChange("Price"); 

      if (_price > 0) 
      { 
       _cost = Math.Round(_price/(decimal)(1.55), 2); 
       NotifyOfPropertyChange("Cost"); 
      }      
     } 
    } 
} 
+0

它帮助我修复循环,但在文本框中我仍然不能插入逗号','和点'。 ',好像文本框不允许插入它们 – puti26

+0

使用转换器将值前后转换。 –