Home > Back-end >  How to use 1 function to diferent UI elemnets like textblock and label or header
How to use 1 function to diferent UI elemnets like textblock and label or header

Time:10-31

There are a way to use 1 function and change regardless the UI element i send like textblock, label, header (from menuItiem)

        private async Task ChangeText(UIelement e,string msg)
        {
          //for the menuItem the ".header" for label: ".content" for textblock: ".text"
            e = msg;
        }

just something like this function or its imposible ?

CodePudding user response:

You will need to decide which property to set depending on the type. Something like this:

private void ChangeText(UIElement e, string msg)
{
    switch (e)
    {
        case TextBlock tb:
            tb.Text = msg;
            break;
        case ContentControl cc:
            if (cc is HeaderedContentControl hcc)
                hcc.Header = hcc;
            else
                cc.Content = msg;
            break;
    }
}

There is no common "text" property for a TextBlock and a ContentControl.

CodePudding user response:

You can use something like this; (available in C# 9.0 and later)

private void ChangeText(UIElement element, string message)
{
    if (element is MenuItem menuItem)
    {
        menuItem.Header = message;
    }
    else if (element is TextBlock textBlock)
    {
        textBlock.Text = message;
    }
    else if (element is Label label)
    {
        label.Content = message;
    }
}
  • Related