在样式中绑定DependencyProperty

本文关键字:DependencyProperty 绑定 样式 | 更新日期: 2023-09-27 18:05:26

我相信这是一件简单的事情,而且可以抬头看,但我还没有任何运气。基本上,我想样式一个WPF滑块,这样当使用时,我可以给它两个额外的字符串显示。

新的控件看起来像这样:

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的作用?

在样式中绑定DependencyProperty

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

您需要在样式和模板中应用自定义控件作为类型。没有它,你试图寻找LeftLabelPropertyRightLabelPropertySlider,而不是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>

已经尝试过这个类你已经发布,它工作得很好:)

相关文章:
  • 没有找到相关文章