简体   繁体   中英

Bind button content to a variable

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

  • 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}"/>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM