繁体   English   中英

在样式中绑定DependencyProperty

[英]Bind DependencyProperty in style

我敢肯定,这是一件简单的事情,而且要查找,但是我还没有任何运气。 基本上,我想设置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的目的?

您只需要一个小修复。 {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>

在您发布的课程中尝试过此方法,效果很好:)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM