-1

Hello people of Stack Overflow. Recently, I've been working on a project in WinUi3, and I haven't been able to find a way to set the content of a Button to a StackPanel.

In WPF you could just do:

myButton.Content = myStackPanel

But in WinUi3, there is no Content property in a button. Here is a sample of the code I'm using:

StackPanel elementPanel = new StackPanel();
elementPanel.Orientation = Orientation.Horizontal;
element.Content = elementPanel; // This doesn't work.
foreach (var item in child.ChildNodes)
{
    if (item.NodeType == HtmlNodeType.Element || item.NodeType == HtmlNodeType.Comment)
    {
        parseElement(item, elementPanel);
    }
}
1
  • You haven't shown where you got "element" from; or how it's defined. Button inherits from ContentControl. Anything that does, has a Content property. A TextBlock doesn't have a "Content" property; it has a Text property instead. Some UI element do not have a Content or Text property and instead have a "Child" property for hosting "content" (small c). Commented Nov 10 at 15:38

1 Answer 1

1

Check the doc and the guidlines, the Button control does have the Content property.

For example:

public sealed partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();

        var elementPanel = new StackPanel();
        elementPanel.Children.Add(new TextBlock { Text = "Hello, World!" });

        var element = new Button();
        element.Content = elementPanel;

        this.Content = element;
    }
}

UPDATE

Based on your comment, it seems that you don't know the type of the element. How about something like this?

private static void SetTextContent(FrameworkElement element, string text)
{
    switch (element)
    {
        // Includes Button, CheckBox, RadioButton, etc.
        case ContentControl contentControl:
            contentControl.Content = text;
            break;
        case TextBlock textBlock:
            textBlock.Text = text;
            break;
        case TextBox textBox:
            textBox.Text = text;
            break;
        // Add more cases as needed for other FrameworkElement types.
        default:
            throw new NotSupportedException($"Element type '{element.GetType().Name}' is not supported.");
    }
}
Sign up to request clarification or add additional context in comments.

2 Comments

Strange. My element doesn't have the content property. I think my program is getting confused as the element isn't always a button, so sometimes it could be a TextBox, or a TextBlock which I'm guessing doesn't have this property?
You need to elaborate more on what that element is. Anyway, I updated my answer. That might help.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.