WPF TemplateBinding连接值的字符串

时间:2016-04-12 23:36:33

标签: c# wpf xaml controltemplate templatebinding

我想将自定义属性(通过依赖属性)添加到我的自定义ToggleButton模板。 现在我希望将包含Label的值(作为将来实现的占位符)作为连接值,比如说“Hello”和实际的Property Value。

没有连接就可以正常工作(在标签上显示“Warrior”)

但是当我尝试将标签设置为串联时,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);
    }
}

1 个答案:

答案 0 :(得分: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>