1

我想将自定义属性(通过依赖属性)添加到我的自定义切换按钮模板中。现在我想让包含标签的值(作为未来实现的占位符)成为一个连接值,比如“你好”和实际的属性值。

没有串联它工作正常(在标签上显示“战士”)

但是当我尝试将标签设置为串联时,xaml 不再编译。

<Label Content="Hello {TemplateBinding local:HeroClassCheckbox.HeroClass}"/>

我怎样才能做到这一点?

代码的其余部分:

我的 .xaml

<Window.Resources>
    <ResourceDictionary>
        <Style x:Key="HeroClassCheckbox" TargetType="ToggleButton">
            <Setter Property="Content" Value="Green" />
            <Setter Property="local:HeroClassCheckbox.HeroClass" Value="NoClass"/>
            <Setter Property="Template">
                <Setter.Value>
                    <ControlTemplate TargetType="{x:Type ToggleButton}">
                        <Label Content="{TemplateBinding local:HeroClassCheckbox.HeroClass}"/>
                    </ControlTemplate>
                </Setter.Value>
            </Setter>
        </Style>
    </ResourceDictionary>
</Window.Resources>
<Grid>
    <ToggleButton Width="150" Height="50" local:HeroClassCheckbox.HeroClass="Warrior" Style="{DynamicResource HeroClassCheckbox}"/>
</Grid>

我的 .xaml.cs

public static class HeroClassCheckbox
{
    public static readonly DependencyProperty HeroClassProperty = DependencyProperty.RegisterAttached("HeroClass",
        typeof(string), typeof(HeroClassCheckbox), new FrameworkPropertyMetadata(null));

    public static string GetHeroClass(UIElement element)
    {
        if (element == null)
            throw new ArgumentNullException("element");
        return (string)element.GetValue(HeroClassProperty);
    }
    public static void SetHeroClass(UIElement element, string value)
    {
        if (element == null)
            throw new ArgumentNullException("element");
        element.SetValue(HeroClassProperty, value);
    }
}
4

1 回答 1

1

您应该使用转换器作为实现目标的方法。这是一个例子..

    public class HelloLabelConverter : IValueConverter
    {
            public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
            {
                    char[] removeThis = "Hello ".ToCharArray();
                    return value.ToString().TrimStart(removeThis);
            }

            public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
            {
                    return string.Format("Hello {0}", value);
            }
    }

   <Window.Resources>
            <local:HelloLabelConverter x:Key="HelloLabelConverter" />
   </Window.Resources>
   <Grid>
       <Label Content="{Binding ElementName= lblPropertyToBind, Path=Text, Converter={StaticResource HelloLabelConverter}}"></Label>
   </Grid>
于 2016-04-12T23:51:45.340 回答