2

我正在编写一个 WPF 应用程序,并且我有一个绑定到文本框的滑块,反之亦然。

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

我希望滑块值随着用户在文本框中键入文本或用户在文本框中按下回车键而改变。

这是我的代码:

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

2 回答 2

4

默认情况下,当控件失去焦点时会更新绑定。这就是为什么您只在单击 TextBox 时才看到变化的原因。您可以使用Binding的UpdateSourceTrigger属性更改此设置,如下所示:

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

现在 TextBox 将在 Text 属性更改时更新其源,而不是在失去焦点时。

于 2012-09-14T09:45:12.527 回答
1

UpdateSourceTrigger属性设置BindingPropertyChanged

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

在这里查看更多

于 2012-09-14T09:47:46.060 回答