Passing a string parameter to a textblock

前提是你 提交于 2019-12-25 03:32:57

问题


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>


来源:https://stackoverflow.com/questions/27193549/passing-a-string-parameter-to-a-textblock

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!