2012-09-14 24 views
2

我在写一个WPF应用程序,并且我有一个绑定到文本框的滑块,反之亦然。根据文本框动态更新WPF滑块

我的问题是,当更改文本框的值时,我必须在更新滑块的值之前单击文本框。

我希望当用户在文本框中输入文本或当用户在文本框中按下Enter键时,滑块值会改变。

继承人的代码,我有:

XAML:

<Slider Name="sldrConstructionCoreSupplierResin" Minimum="0" Maximum="10" Grid.Column="1" Grid.Row="1" IsSnapToTickEnabled="True"/> 
    <TextBox Name="txtConstructionCoreSupplierResin" Text="{Binding ElementName=sldrConstructionCoreSupplierResin, Path=Value, Converter={StaticResource RoundingConverter}}" Grid.Column="2" Grid.Row="1"/> 

代码背后:

public class RoundingConverter : IValueConverter 
    { 
     public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) 
     { 
      if (value != null) 
      { 
       double dblValue = (double)value; 
       return (int)dblValue; 
      } 
      return 0; 
     } 

     public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) 
     { 
      if (value != null) 
      { 
       int ret = int.Parse(value.ToString()); 
       return ret; 
      } 
      return 0; 
     } 
    } 

回答

4

默认情况下,当控件失去焦点绑定更新。这就是为什么当您单击TextBox时只能看到更改。您可以使用绑定的UpdateSourceTrigger财产,像这样改变这种:

<TextBox Text="{Binding Value,ElementName=mySlider,UpdateSourceTrigger=PropertyChanged}" /> 

现在文本框将更新其源每当Text属性的变化,而不是当它失去焦点。

+0

感谢这个,虽然我认为你需要将其更改为UpdateSourceTrigger,那么既然你回答,我首先为纪念UpdateSourceTrigger财产正确:) – user589195

+0

糟糕。没有编译器来仔细检查我的代码。 :) –

1

设置的BindingPropertyChanged

<TextBox Text="{Binding ElementName=sldrConstructionCoreSupplierResin, Path=Value, UpdateSourceTrigger = "PropertyChanged" Converter={StaticResource RoundingConverter}}"/> 

查看更多here