Embedd_0913
Embedd_0913

Reputation: 16555

WPF data binding issue

I am just new to WPF.

I have a wpf app and there i simply have a dock panel and inside dock panel i have a textblock.

I want to bind the text property of textblock to my custom object's property but that' not working.

I think i am missing something here but don't know what.

Here is the code snippet.

      <TextBlock Text="{Binding Source=myDataSource, Path=ColorName}"/>
</DockPanel>

My custom class.

class MyData
    {
        public string ColorName { get; set; }
}

and main window constructor..

public partial class MainWindow : Window
    {
        MyData myDataSource;
        public MainWindow()
        {
            InitializeComponent();
            myDataSource = new MyData { ColorName = "Red" };
    }
}

Upvotes: 0

Views: 386

Answers (3)

Alex P
Alex P

Reputation: 26

If you only want to bind to MyData, don't set window as its own DataContext. Istead, set the data you're binding to. This way it's more clear what is data, and what is view.

Also, lose the Source on Binding, you won't generally need it.

public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
        this.DataContext = new MyData { ColorName = "Red" };
    }
}

public class MyData
{
    public string ColorName { get; set; }
}

XAML:

<TextBlock Text="{Binding ColorName}"/>

Upvotes: 0

brunnerh
brunnerh

Reputation: 184516

  1. What you bind to needs to be a public property. (Your data-object needs to satisfy that condition as well)
  2. Unless you set the property before InitializeComponent() the binding will might not update depending on your binding.
  3. If you set it again at any point in time after the initilization and want the binding to be updated you should implement INotifyPropertyChanged or work with dependency properties.
  4. Since the data is in your window you might need to access it over that: {Binding ElementName=window, Path=myDataSource.ColorName}

Upvotes: 0

Jason Quinn
Jason Quinn

Reputation: 2563

myDataSource needs a get and set. You also need to set the dataContext for the window, so it should be-

public partial class MainWindow : Window
{
    public MyData MyDataSource { get; set; }
    public MainWindow()
    {
        InitializeComponent();
        this.DataContext = this;
        MyDataSource = new MyData { ColorName = "Red" };
    }
}

public class MyData
{
    public string ColorName { get; set; }
}

and xaml code should be -

<TextBlock Text="{Binding MyDataSource.ColorName}"/>

edit Sorry got this wrong I've changed to the correct code

Upvotes: 1

Related Questions