1

我确信这是一件简单的事情,而且要抬头看,但我还没有运气。基本上我想设计一个 WPF Slider 的样式,这样在使用时我可以给它两个额外的字符串来显示。

新控件如下所示:

public class SliderPicker : Slider
{
    public string LeftLabel
    {
        get { return (string)GetValue(LeftLabelProperty); }
        set { SetValue(LeftLabelProperty, value); }
    }

    public static readonly DependencyProperty LeftLabelProperty =
        DependencyProperty.Register("LeftLabel", typeof(string), typeof(SliderPicker), new UIPropertyMetadata(String.Empty));

    public string RightLabel
    {
        get { return (string)GetValue(RightLabelProperty); }
        set { SetValue(RightLabelProperty, value); }
    }

    public static readonly DependencyProperty RightLabelProperty =
        DependencyProperty.Register("RightLabel", typeof(string), typeof(SliderPicker), new UIPropertyMetadata(String.Empty));
}

像这样的风格:

    <Style x:Key="SlickSlider" TargetType="{x:Type Slider}">
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="{x:Type Slider}">
                    ...
                            <TextBlock Text="{TemplateBinding LeftLabel}" Grid.Row="2" HorizontalAlignment="Left" />
                            <TextBlock Text="{TemplateBinding RightLabel}" Grid.Row="2" HorizontalAlignment="Right" />
                        </Grid>
                    </Border>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
    </Style>

和用法:

<controls:SliderPicker LeftLabel="RealPreference" RightLabel="RealCoverage" Width="400" Style="{StaticResource SlickSlider}"/>

这似乎不起作用。那么,如何在控件上设置DP并在模板中显示呢?我以为这就是 TemplateBinding 的用途?

4

1 回答 1

1

你只需要一个小的修复。更改{x:Type Slider}{x:Type controls:SliderPicker}

您需要将自定义控件应用为样式和模板中的类型。没有它,您将尝试查找LeftLabelPropertyRightLabelProperty输入,Slider而不是SliderPicker使用模板绑定。

改变你的风格

<Style x:Key="SlickSlider" TargetType="{x:Type controls:SliderPicker}">
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="{x:Type controls:SliderPicker}">
                    ...
                            <TextBlock Text="{TemplateBinding LeftLabel}" Grid.Row="2" HorizontalAlignment="Left" />
                            <TextBlock Text="{TemplateBinding RightLabel}" Grid.Row="2" HorizontalAlignment="Right" />
                        </Grid>
                    </Border>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
    </Style>

已在您发布的课程中尝试过此操作,并且效果很好:)

于 2013-03-22T18:30:24.090 回答