简体   繁体   中英

A Usercontrol with just a TextBlock. How do I expose the TextWrapping property to the consumer?

I have a minimalist UserControl containing a single TextBlock which I prototype as follows:

<Grid>
    <TextBlock x:Name="textBlockExt" x:FieldModifier="public"/>
</Grid>
public partial class TextBlockExt : UserControl
{
    public TextBlockExt()
    {
        InitializeComponent();

        DataContext = this;
    }

    public string Text
    {
        get => textBlockExt.Text;
        set { textBlockExt.Text = value.ToUpper(); } // to be expanded later
    }
}

I then consume the control by

<Grid>
    <StackPanel>
        <local:TextBlockExt FontSize="30" x:Name="txb" Text="Hello World" TextBlock.TextAlignment="Center"/>
        <Button Content="To Upper" Width="100" Click="Button_Click"/>
    </StackPanel>
</Grid>

And it's code behind is

public MainWindow()
{
    InitializeComponent();

    txb.textBlockExt.TextWrapping = TextWrapping.WrapWithOverflow;
}

private void Button_Click(object sender, RoutedEventArgs e)
{
    txb.Text = "one two three four five six seven eight";
}

I don't like the code in the MainWindow constructor above and need to know how to set the T extWrapping in the XAML.

Add a property TextWrapping to your TextBlockExt class. Use the same way you did for the Text property:

public TextWrapping TextWrapping {
    get => txtBlockExt.TextWrapping;
    set { txtBlockExt.TextWrapping = value: }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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