Home > database >  WPF Button multiple text lines access
WPF Button multiple text lines access

Time:01-25

I made style for button

<Style x:Key="ButtonList"
       TargetType="Button">
    <Setter Property="HorizontalAlignment"
            Value="Stretch" />
    <Setter Property="Background"
            Value="Aqua" />
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="{x:Type Button}">
                <Border BorderBrush="{TemplateBinding BorderBrush}" Background="{TemplateBinding Background}" Padding="5" BorderThickness="1">
                <StackPanel VerticalAlignment="Stretch"
                            HorizontalAlignment="Stretch">

                    <TextBlock x:Name="AText" />
                    <TextBlock x:Name="BText" HorizontalAlignment="Right" />

                </StackPanel>
                </Border>
            </ControlTemplate>
        </Setter.Value>
    </Setter>

How can I sett the Text of "Atext" textblock and "BText" textblock seperate from codebehind?

CodePudding user response:

Create a AttachedProperty for Button(or you can create a customControl based on Button) named with ContentB.

<TextBlock x:Name="AText" Text={TemplateBinding Content}/>
<TextBlock x:Name="BText" Text={TemplateBinding ap:ContentB} HorizontalAlignment="Right" />

In cs code,you can access Button.Content and Button.ContentB

2.Another method:

<TextBlock x:Name="AText" Text={TemplateBinding Content,Converter={StaticSource ContentConverter},ConverterParameter=1}/>
<TextBlock x:Name="BText" Text={TemplateBinding Content,Converter={StaticSource ContentConverter},ConverterParameter=2} HorizontalAlignment="Right" />

ContentConverter.cs Code:

internal class ContentConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        if (value is string valuestring)
        {
            return valuestring.Split(',')[(int)parameter-1];
        }
        return value;
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        throw new NotImplementedException();
    }
}

oh,You need to use a separator e.g. commas to separate the two text pieces

  •  Tags:  
  • Related