更改Slider上的绑定模式会导致更改值

时间:2013-09-03 07:46:23

标签: wpf

我在启动时启用了twoway绑定的滑块。但是当我移动它们时,移动并不顺利。因此,我决定在调用Thumbs.DragStarted事件后将绑定模式从twoway更改为onewaytosource,但这会导致立即将值从1更改为0.

我的问题是:如何在新绑定期间阻止滑块更改其值?

我的代码背后是。

    private void SliderCameraZ_OnDragStarted(object sender, DragStartedEventArgs e)
    {
        try
        {
            BindingExpression bindingExpression = ((Slider) sender).GetBindingExpression(Slider.ValueProperty);
            BindingOperations.ClearBinding((Slider) sender, Slider.ValueProperty);
            Binding binding = new Binding();
            binding.Path = bindingExpression.ParentBinding.Path;
            binding.Mode = BindingMode.OneWayToSource;
            binding.UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged;
            ((Slider)sender).SetBinding(Slider.ValueProperty, binding);

        }
        catch (Exception exception)
        {
            MessageBox.Show(exception.Message + exception.StackTrace + exception.TargetSite);
        }
    }

2 个答案:

答案 0 :(得分:1)

在大多数情况下,使用.Net 4.5中引入的Delay Property来减少更新调用需要花费很多时间。有关示例,请参阅Adding a delay to your binding updates to reduce noise

<StackPanel>
    <Slider x:Name="ValueSlider"
            Minimum="0" Maximum="100"
            Margin="20" Height="25"
            Value="{Binding ElementName=ValueText, Delay=500, Path=Text, Mode=TwoWay}" />
    <TextBox x:Name="ValueText" Text="50"
             Width="100" Height="50" FontSize="20"
             HorizontalAlignment="Center" /> 
</StackPanel>

如果您确实需要立即更新,仍然可以致电BindingExpression.UpdateSource Method各自BindingExpression.UpdateTarget Method

BindingExpression bindingExpression = ValueSlider.GetBindingExpression(Slider.ValueProperty);
bindingExpression.UpdateSource();

但您的问题是在更改绑定模式后阻止值更改。我注意到这只会出现BindingMode.OneWayToSource。也许您可以通过将上面的示例更改为

来避免这种情况
<StackPanel>
    <Slider x:Name="ValueSlider"
            Minimum="0" Maximum="100"
            Margin="20" Height="25"
            Value="50" />
    <TextBox x:Name="ValueText"
             Text="{Binding ElementName=ValueSlider, Path=Value, Mode=TwoWay}"
             Width="100" Height="50" FontSize="20"
             HorizontalAlignment="Center" /> 
</StackPanel>

现在TextBox绑定到Slider而不是相反。{ BindingMode.OneWayToSourceBindingMode.OneWay,绑定更改不应导致值更改。

BindingExpression bindingExpression = ValueText.GetBindingExpression(TextBox.TextProperty);
Binding binding = new Binding();
binding.Source = bindingExpression.DataItem;
binding.Path = bindingExpression.ParentBinding.Path;
binding.Mode = BindingMode.OneWay;
binding.UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged;
ValueText.SetBinding(TextBox.TextProperty, binding);

答案 1 :(得分:0)

一切都很简单。我只需要存储滑块的值并在设置新绑定后恢复它。