将字符串参数传递给文本块 [英] Passing a string parameter to a textblock

查看:64
本文介绍了将字符串参数传递给文本块的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图将一个字符串参数从另一个 xaml 页面(通过单击按钮)传递到内容对话框中,并以另一种颜色显示在文本块中.

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.

文本块文本示例:

嘿-红色参数-,好吧-蓝色参数-,...一些文字...-另一种颜色的参数-

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.

冗余代码太多,我相信有一个更优雅的解决方案,我希望有人能指出我正确的方向.有些东西告诉我它具有约束力,但我不确定如何继续.(我是 XAML 的新手,并试图从一些简单的事情开始寻找出路)

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)

推荐答案

您可以将一个对象设置为 ContentDialog.DataContext,然后使用绑定来实现您想要的.

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

在您的 Button.Click 处理程序中,设置数据上下文:

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();
}

然后在 ContentDialog 的 XAML 中,您可以具有以下内容:

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>

这篇关于将字符串参数传递给文本块的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆