How can I create a bindable property as in the TextBlock in UMG or any other class?
I did try to see what’s inside the TextBlock class, and I ended up having this:
using this code only:
public:
/** The text to display */
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "Data", meta = (MultiLine = "true", ExposeOnSpawn = "True"))
FText Text = FText::FromString("TextBlock");
/** A bindable delegate to allow logic to drive the text of the widget */
UPROPERTY()
FGetText TextDelegate;
protected:
// Macro implementation for Text property
PROPERTY_BINDING_IMPLEMENTATION(FText, Text);
but the “GetText” function doesn’t fire, so the value doesn’t change.
but it works when I use it in the Engine’s “Textblock”
tried to implement more code from the Textblock class, and still no change, here is the full code now:
.h file:
// Copyright © 2024 Nova Electron. All rights reserved.
#pragma once
#include "CoreMinimal.h"
#include "CommonUserWidget.h"
#include "W_Text.generated.h"
class UW_CommonTextBlock;
class UW_Background;
UCLASS(Abstract)
class UW_Text : public UCommonUserWidget
{
GENERATED_BODY()
protected:
/* Widget Content */
UPROPERTY(BlueprintReadWrite, meta = (BindWidget), Category = "WBP-Refs")
TObjectPtr<UW_CommonTextBlock> CommonTextBlock;
UPROPERTY(BlueprintReadWrite, meta = (BindWidget), Category = "WBP-Refs")
TObjectPtr<UW_Background> Background;
public:
/** The text to display */
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "Data", meta = (MultiLine = "true", ExposeOnSpawn = "True"))
FText Text = FText::FromString("TextBlock");
// This function will update the property from outside the widget
void SetBindableText(const FText& NewText)
{
Text = NewText;
}
/** A bindable delegate to allow logic to drive the text of the widget */
UPROPERTY()
FGetText TextDelegate;
virtual TAttribute<FText> GetDisplayText();
virtual void SynchronizeProperties() override;
virtual void OnBindingChanged(const FName& Property) override;
protected:
TSharedPtr<STextBlock> MyTextBlock;
// Macro implementation for Text property
PROPERTY_BINDING_IMPLEMENTATION(FText, Text);
};
.cpp file:
// Copyright © 2024 Nova Electron. All rights reserved.
#include "W_Text.h"
void UW_Text::OnBindingChanged(const FName& Property)
{
Super::OnBindingChanged(Property);
if (MyTextBlock.IsValid())
{
static const FName TextProperty(TEXT("TextDelegate"));
if (Property == TextProperty)
{
TAttribute<FText> TextBinding = GetDisplayText();
MyTextBlock->SetText(TextBinding);
}
}
}
void UW_Text::SynchronizeProperties()
{
Super::SynchronizeProperties();
TAttribute<FText> TextBinding = GetDisplayText();
if (MyTextBlock.IsValid())
{
MyTextBlock->SetText(TextBinding);
}
}
TAttribute<FText> UW_Text::GetDisplayText()
{
return PROPERTY_BINDING(FText, Text);
}