1

I have the following in XAML:

<Button Content="{Binding KB.Text}" />

KB is an instance of the following class:

public class ButtonText
    {
        public string Text
        {
            get
            {
                return "Button";
            }
        }
    }

I have KB defined as global variable in the code behind of the page, the button content is showing empty when running the project, how would I achieve this? The button content should be retrieved by KB.Text

Romasz
  • 29,662
  • 13
  • 79
  • 154
Green Train
  • 223
  • 3
  • 14

1 Answers1

3
  • Make sure that your "KB" object is initialized (not null).

  • You might have missed "this.DataContext = this" in your main function

  • Make sure your KB is property

This works for me:

public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
        this.DataContext = this;
        KB = new ButtonText();
    }

    public ButtonText KB { get; }

}
public class ButtonText
{
    public string Text
    {
        get
        {
            return "Button";
        }
    }
}

EDIT: I wrote the first solution having in mind WPF, took me a while to figure there's a "UWP" tag.

In UWP, if you want to bind something to the code behind of the designer itself (*xaml.cs), you should use "x:Bind" instead of "Binding".

See the link about x:Bind vs Binding

In short, your xaml should look like so:

<Button Content="{x:Bind KB.Text}"/>
MaxB
  • 438
  • 6
  • 15
  • Hmm, doesn't work for me, could it because my main class inherits from Page instead of Window? or maybe I need to define a xmlns property? I've tried it on a new project as well. – Green Train Mar 25 '18 at 09:52
  • @Ham.Abdu2 Sorry, I forgot it's UWP and not WPF. I updated my answer – MaxB Mar 25 '18 at 10:35
  • How this is supposed to work? The KB is initialized after setting the datacontext, therefore UI won't have correct value. Also without INotifyPropertyChanged further changes to KB won't notify UI. – Romasz Mar 25 '18 at 20:28