共用方式為


WidgetManager.UpdateWidget(WidgetUpdateRequestOptions) 方法

定義

為小工具主機提供小工具的更新內容。

public:
 virtual void UpdateWidget(WidgetUpdateRequestOptions ^ widgetUpdateRequestOptions) = UpdateWidget;
void UpdateWidget(WidgetUpdateRequestOptions const& widgetUpdateRequestOptions);
public void UpdateWidget(WidgetUpdateRequestOptions widgetUpdateRequestOptions);
function updateWidget(widgetUpdateRequestOptions)
Public Sub UpdateWidget (widgetUpdateRequestOptions As WidgetUpdateRequestOptions)

參數

widgetUpdateRequestOptions
WidgetUpdateRequestOptions

WidgetUpdateRequestOptions物件,其中包含要用來更新小工具的內容。

實作

範例

下列程式碼範例示範 UpdateWidget的一般用法。 WidgetManager.GetWidgetInfos() 會呼叫 來取得與小工具提供者相關聯之使用中小工具的物件清單 WidgetInfo 。 針對每個小工具,會產生視覺化範本和資料範本,並傳遞至WidgetUpdateRequestOptions物件中的UpdateWidget呼叫。

using namespace winrt;
using namespace Microsoft::Windows::Widgets;
using namespace Microsoft::Windows::Widgets::Providers;

class WidgetManagerOperations
{
    void InitializeWidgets(hstring myWidgetId)
    {
        WidgetManager widgetManager = WidgetManager::GetDefault();
        com_array<WidgetInfo> widgetInfos = widgetManager.GetWidgetInfos();

        for (const auto& widgetInfo : widgetInfos)
        {
            if (widgetInfo.WidgetContext().IsActive())
            {
                WidgetUpdateRequestOptions options{myWidgetId};
                options.Template(LR"({
                    "type": "AdaptiveCard",
                    "version": "1.5",
                    "body": [
                        {
                            "type": "TextBlock",
                            "text": "${greeting}"
                        }
                    ]
                })");

                options.Data(LR"({
                    "greeting": "Hello"
                })");

                widgetManager.UpdateWidget(options);
            }
        }
    }
}

備註

不會更新 WidgetUpdateRequestOptions類別中未設定的任何變數。 例如,如果您只想要更新小工具的資料,但您想要保留現有的視覺化範本和自訂狀態,則只要 WidgetUpdateRequestOptions.Data 設定 屬性,小工具的資料就會更新,但不會修改範本和自訂狀態。

UpdateWidget 也可用來清除任何預存值,方法是設定要清除值的空字串。 例如,如果您想要清除小工具的預存自訂狀態,您可以將 屬性設定 WidgetUpdateRequestOptions.CustomState 為空字串,這會在呼叫 UpdateWidget 之後清除儲存的自訂狀態。

呼叫此函式來更新已刪除的小工具、未與您的應用程式相關聯的小工具,或使用不存在的小工具識別碼,將會導致忽略更新。

適用於