combobox1.SelectedItem
绑定到SelectedItemProperty
。SelectedItemProperty
时,计算MaxValueProperty
MaxValueProperty
绑定到slider1.Maximum
slider1.Value
绑定到SliderValueProperty
这些都可以正常工作,除非combobox1.SelectedItem
更改,MaxValueProperty
已计算,并且小于SliderValueProperty
。
在视图中:
slider1.Maximum
已更新,因为MaxValueProperty
已更改,slider1.Value
设置为slider1.Maximum
作为滑块的默认行为,当max更改为小于该值时。但是,如果发生这种情况,SliderValueProperty
不会更新为新slider1.Value
<Slider Name="slider1" Maximum="{Binding Path=MaxValueProperty, Mode=TwoWay}" Value="{Binding Path=SliderValueProperty, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" />
我知道slider1.Value正在改变,因为我有一个标签绑定它,标签改变了
<Label Content="{Binding ElementName=slider, Path=Value, Converter={StaticResource NumberToStringConverter}}" />
如何确保更新绑定?
答案 0 :(得分:0)
在计算TwoWay
setter PropertyChanged绑定,而是引发SelectedItemProperty
事件>,首先使用新的最大值在“SliderValueProperty”上,然后在“MaxValueProperty”上使用第二个。在您的私人支持字段上进行计算,而不是在公共属性上进行计算。
这将导致系统首先调整滑块的值,然后调整maxvalue,它应该为您移动滑块位置。
将slider1的Maximum
上的绑定模式设置为OneWay
;我认为这样做会有所帮助。
如下所示使用这样的viewmodel:
Class viewmodel
Implements INotifyPropertyChanged
Private _selectedItemProperty As ComboBoxItem
Public Property SelectedItemProperty As ComboBoxItem
Get
Return _selectedItemProperty
End Get
Set(value As ComboBoxItem)
MaxValueProperty = value.Content
If _sliderValueProperty > _maxValueProperty Then _sliderValueProperty = _maxValueProperty
RaiseEvent PropertyChanged(Me, New PropertyChangedEventArgs("MaxValueProperty"))
RaiseEvent PropertyChanged(Me, New PropertyChangedEventArgs("SliderValueProperty"))
End Set
End Property
Private _maxValueProperty, _sliderValueProperty as Single
Public Property MaxValueProperty As Single ' with setter that will raise PropertyChanged and use the backing field
'...
Public Property SliderValueProperty As Single ' with a setter that will raise PropertyChanged and use the backing field
'...
End Class
XAML看起来有点像这样:
<Grid>
<ComboBox Height="23" HorizontalAlignment="Left" Margin="40,38,0,0" Name="ComboBox1" VerticalAlignment="Top" Width="120" SelectedItem="{Binding SelectedItemProperty}">
<ComboBoxItem Content="50" />
<ComboBoxItem Content="30" />
<ComboBoxItem Content="10" />
</ComboBox>
<Slider Name="slider1" Height="23" HorizontalAlignment="Left" Margin="87,135,0,0" VerticalAlignment="Top" Width="100" Value="{Binding SliderValueProperty}" Minimum="1" Maximum="{Binding MaxValueProperty}" />
<Label Content="{Binding ElementName=slider1, Path=Value}" Margin="40,174,293,96" />
</Grid>