Reputation: 16555
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
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
Reputation: 184516
InitializeComponent()
the binding
will might not update depending on your binding.INotifyPropertyChanged
or work
with dependency properties.Upvotes: 0
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