我有一个滑块绑定到DoubleCollection Ticks(通过Ticks =“{Binding Ticks}”),它有一组值。 Ticks集合最终被清除并填充完全不同的值。问题是,在重新填充之后,即使集合中的值已经不同,滑块仍会按旧标记移动。
如何解决这个问题?
答案 0 :(得分:0)
似乎tick集合不依赖于最小值和最大值。
滑块值取决于最小值和最大值,刻度仅为“装饰”。
以上示例应该有效。
基本上,在更改ticks集合时,我会更改Minimum
和Maximum
绑定值以适合tick集合的最小值和最大值。
C#部分:
public partial class MainWindow : Window,INotifyPropertyChanged
{
private double _value;
private double _minimum;
private double _maximum;
private DoubleCollection _tickCollection;
public MainWindow()
{
InitializeComponent();
DataContext = this;
TickCollection = new DoubleCollection();
for (double i = 0.0; i < 5.0; i+=0.5)
{
TickCollection.Add(i);
}
Minimum = 0.0;
Maximum = 5.0;
Value = 2.3;
}
public double Value
{
get { return _value; }
set
{
_value = value;
OnPropertyChanged();
}
}
public double Minimum
{
get { return _minimum; }
set { _minimum = value; OnPropertyChanged(); }
}
public double Maximum
{
get { return _maximum; }
set { _maximum = value; OnPropertyChanged(); }
}
public DoubleCollection TickCollection
{
get { return _tickCollection; }
set
{
_tickCollection = value;
OnPropertyChanged();
}
}
private void ButtonBase_OnClick(object sender, RoutedEventArgs e)
{
TickCollection = new DoubleCollection();
for (double i = 5.0; i < 10.0; i += 1.0)
{
TickCollection.Add(i);
}
Minimum = 5.0;
Maximum = 10.0;
Value = 2.3;
}
public event PropertyChangedEventHandler PropertyChanged;
[NotifyPropertyChangedInvocator]
protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
XAML Conterpart:
<Grid>
<Slider x:Name="mySlider" Width="400" Height="40" Ticks="{Binding TickCollection}"
TickPlacement="TopLeft"
Minimum="{Binding Minimum}"
Maximum="{Binding Maximum}"
Value="{Binding Value,Mode=TwoWay}"
></Slider>
<TextBlock Text="{Binding Value}" HorizontalAlignment="Center" Margin="0,20" VerticalAlignment="Top"></TextBlock>
<Button Content="Change Ticks" Click="ButtonBase_OnClick" HorizontalAlignment="Center" Margin="0,60" VerticalAlignment="Top"></Button>
</Grid>