Binding a slider value on the height of its thumb in WPF

天大地大妈咪最大 提交于 2019-12-14 03:53:14

问题


I have a databinding problem in WPF.

I would like to "customise" a slider in a way that the thumb grows when you move the slider to the right and the thumb shrinks when you move the slider to the left.

So I edited the template for the slider and changed the look of the slider so the slider looks like I want it to.

But now I have to bind the height of the thumb to the value of the slider but I do not know how that works.

I did some simple data binding things but I cannot figure out how I can bind this "thumb height" that's inside of my slider's template to the slider's value that's inside the User Control where my slider is in.

So how can I do it?


回答1:


You can use RelativeSource binding (Height="{Binding Value, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type Slider}}}").

Here is an example of the thumb style, that depends on Slider.Value:

<Style x:Key="SliderThumbStyle" TargetType="{x:Type Thumb}">
  <Setter Property="SnapsToDevicePixels" Value="true"/>
  <Setter Property="OverridesDefaultStyle" Value="true"/>
  <Setter Property="Width" Value="14"/>
  <Setter Property="Template">
    <Setter.Value>
      <ControlTemplate TargetType="{x:Type Thumb}">
        <Ellipse 
          Name="Ellipse" 
          Fill="#C0C0C0"
          Stroke="#404040" 
          Height="{Binding Value, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type Slider}}}"
          StrokeThickness="1" />
        <ControlTemplate.Triggers>
          <Trigger Property="IsMouseOver" Value="True">
            <Setter TargetName="Ellipse" Property="Fill" Value="#808080"/>
          </Trigger>
          <Trigger Property="IsEnabled" Value="false">
            <Setter TargetName="Ellipse" Property="Fill" Value="#EEEEEE"/>
          </Trigger>
        </ControlTemplate.Triggers>
      </ControlTemplate>
    </Setter.Value>
  </Setter>
</Style>

Hope this helps.

Cheers Anvaka




回答2:


Check my question and answer here -

In WPF/XAML how do I change the size of a paragraph of text using a scroll bar?

If you have something like this:

<ScrollBar x:Name="scroll1"></ScrollBar>

<Image Height="{Binding ElementName=scroll1, Path=Value}" />

NB I'm not 100% sure of the syntax for the image, so you'll need to take this as pseudo code.



来源:https://stackoverflow.com/questions/2689406/binding-a-slider-value-on-the-height-of-its-thumb-in-wpf

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!