Passing a string parameter to a textblock

2019-08-26 09:08发布

问题:

I am trying to pass a string parameter from another xaml page (upon click of a button) into a content dialog and display it inside a textblock in another colour.

Example of the textblock text:

Hey -parameter in red colour-, well -parameter in blue colour-, ... some text... -parameter in another colour-

My current method is to create several textblocks with different properties and then programmatically set the text to the corresponding textblock in the constructor.

There are too much redundant code and I believe there is a more elegant solution to this and I hope that someone could point me in the correct direction. Something tells me its binding but I am not sure how to proceed. (I'm new to XAML and trying to figure my way out by starting on something simple)

回答1:

You can have an object set as the ContentDialog.DataContext and then use binding to achieve what you want.

In your Button.Click handler, set the data context:

private void Button_Click(object sender, RoutedEventArgs args)
{
    ContentDialog dialog = new ContentDialog
    {
        DataContext = new
        {
            RedText = "Red Colour",
            BlueText = "Blue Colour"
        }
    };

    dialog.ShowAsync();
}

Then in the XAML of the ContentDialog, you can have something as:

<ContentDialog>
    <TextBlock>Hey <TextBlock Background="Red" Text="{Binding RedText}"/>, well <TextBlock Background="Blue" Text="{Binding BlueText}"/></TextBlock>
</ContentDialog>