如何在C#代码中动态更改自定义自适应卡的文本属性值?
这是我的C#代码
public static Attachment CreateMySearchCardAttachment()
{
// combine path for cross platform support
string[] paths = { ".", "Resources", "MySearchCard.json" };
var MySearchCardJson = File.ReadAllText(Path.Combine(paths));
var adaptiveCardAttachment = new Attachment()
{
ContentType = "application/vnd.microsoft.card.adaptive",
Content = JsonConvert.DeserializeObject(MySearchCardJson),
};
return adaptiveCardAttachment;
}
我的 MySearchCard.json 文件位于下面
{
"type": "AdaptiveCard",
"body": [
{
"type": "ColumnSet",
"columns": [
{
"type": "Column",
"items": [
{
"type": "Image",
"horizontalAlignment": "Right",
"spacing": "None",
"url": "",
"size": "Medium",
"width": "2px",
"height": "2px"
},
{
"type": "TextBlock",
"size": "Medium",
"weight": "Bolder",
"text": "Knowledgebase Search"
},
{
"type": "Input.Text",
"id": "searchText",
"placeholder": "Type your search text and click Search"
}
],
"width": 2
}
]
}
],
"actions": [
{
"type": "Action.Submit",
"title": "Search"
}
],
"$schema": "http://adaptivecards.io/schemas/adaptive-card.json",
"version": "1.0"
}
如果您查看我的json,有一个文本属性为“ text”:“ Knowledgebase Search”。我的问题是如何从我的C#代码中动态更改此文本值?
答案 0 :(得分:0)
有几种不同的方法可以做到这一点。第一个选项可能是最好的,但是它们都应该起作用。
注意:此软件包不同于Microsoft.AdaptiveCards,并且比更新-请勿使用此软件包
由于您知道要更改的卡片的确切部分,因此可以:
string[] paths = { ".", "AdaptiveCard.json" };
var cardJson = File.ReadAllText(Path.Combine(paths));
var card = AdaptiveCard.FromJson(cardJson).Card;
var columnSet = (card.Body[0] as AdaptiveColumnSet);
var column = (columnSet.Columns[0] as AdaptiveColumn);
var knowledgeBlock = (column.Items[1] as AdaptiveTextBlock);
knowledgeBlock.Text = "Whatever You Want";
var attachment = new Attachment()
{
Content = card,
ContentType = "application/vnd.microsoft.card.adaptive"
};
var reply = stepContext.Context.Activity.CreateReply();
reply.Attachments = new List<Attachment>();
reply.Attachments.Add(attachment);
await stepContext.Context.SendActivityAsync(reply);
结果:
这是预览版,您仍然需要使用#1中的NuGet程序包,但可以更轻松地修改特定字段。
UpdateActivityAsync()
这可能会更简单一些,但不太灵活。像这样的东西可以产生和#1相同的结果:
string[] paths = { ".", "AdaptiveCard.json" };
var cardJsonObject = JObject.Parse(File.ReadAllText(Path.Combine(paths)));
var knowledgeToken = cardJsonObject.SelectToken("body[0].columns[0].items[1]");
knowledgeToken["text"] = "Whatever You Want";
var attachment = new Attachment()
{
Content = cardJsonObject,
ContentType = "application/vnd.microsoft.card.adaptive"
};
var reply = stepContext.Context.Activity.CreateReply();
reply.Attachments = new List<Attachment>();
reply.Attachments.Add(attachment);
await stepContext.Context.SendActivityAsync(reply);
return await stepContext.NextAsync();
显示卡后更改卡要困难一些。如上所述,您首先必须在代码中更改卡。然后,您必须使用my answer here。基本上,您发送的活动具有相同的id
,但是有一张新卡,它会完全覆盖前一张卡。
注意:您只能在支持更新活动的渠道中使用此功能。这通常很容易告诉您,因为即使没有漫游器,该频道也会允许或不允许您编辑消息。听起来好像您想使用团队,这样就可以正常工作。
您可以使用other StackOverflow Answer来更新团队的卡片活动。请注意,这是在Node中的,但是您仍然可以以相同的方式在C#中完成它。
您也可以使用MS Teams团队中一位成员的{{3}}。