Home > database >  WPF XAML binding properties within a ControlTemplate
WPF XAML binding properties within a ControlTemplate

Time:01-17

I'm trying to create a ControlTemplate representing a Slider and a TextBox (and a Label), where the text of the TextBox should show the value of the Slider.

I can't figure out how to correctly setup the binding between the Slider's Value property and the TextBox' Text property.

This is my ControlTemplate:

<ControlTemplate x:Key="myslider" TargetType="Slider">
    <StackPanel Orientation="Horizontal" HorizontalAlignment="Left">
        <Label>Slider</Label>
        <Slider 
            Width="100" 
            Minimum="0" Maximum="100"/>
        <TextBox Width="40" 
            Text="{Binding RelativeSource={RelativeSource TemplatedParent}, 
                Path=Value}">
        </TextBox>
    </StackPanel>              
</ControlTemplate>

Here I instantiate 3 Slider using the ControlTemplate:

<StackPanel>
    <Slider Template="{StaticResource myslider}"></Slider>
    <Slider Template="{StaticResource myslider}"></Slider>
    <Slider Template="{StaticResource myslider}"></Slider>
</StackPanel>

This ends up looking like this:

enter image description here

The goal is that each slider controls the value within the indivual TextBoxes.

CodePudding user response:

I would prefer using a User Control as a first choice. But if we follow your line of thought the shared value of the Slider and the TextBox should be the Value dependency property on the parent Slider.

The tested code is as following :

<Window.Resources>
    <ControlTemplate x:Key="myslider" TargetType="Slider">
        <StackPanel Orientation="Horizontal" HorizontalAlignment="Left">
            <Label>Slider</Label>

            <Slider 
                Value="{Binding RelativeSource={RelativeSource TemplatedParent},Path=Value,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged,Delay=10}"
                    
                Minimum="{Binding RelativeSource={RelativeSource TemplatedParent},Path=Minimum,Mode=OneWay}"
                    
                Maximum="{Binding RelativeSource={RelativeSource TemplatedParent},Path=Maximum,Mode=OneWay}"
                    
                Width="100" 
                />

            <TextBox Width="100" 
                Text="{Binding RelativeSource={RelativeSource TemplatedParent}, 
                Path=Value,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged,Delay=10}">
            </TextBox>
                
        </StackPanel>
    </ControlTemplate>
</Window.Resources>
<Grid>
    <StackPanel Orientation="Vertical">

        <Slider Template="{StaticResource myslider}" Minimum="0" Maximum="100"></Slider>
        <Slider Template="{StaticResource myslider}" Minimum="0" Maximum="100"></Slider>
        <Slider Template="{StaticResource myslider}" Minimum="0" Maximum="100"></Slider>
    </StackPanel>
        
</Grid>
  • Related