Reputation: 6444
I'm new to both C# and WPF. I've written a simple program. I have a class called Counter
, that exposes a read-only property Count
that starts out at 0, and a public method Increment
that simply increments the count by one. Counter
implements INotifyPropertyChanged
.
I have a Window class (code is below). I pass an instance of a Counter
object to the constructor and perform a binding. The window has a button and a label. The label is bound to the counter's Count
property, and the button calls Increment
.
This all works.
However, most examples I've seen around the net and MSDN mostly deal with defining the binding in XAML. How can I modify my example here to move the binding operation out of code behind and into the markup? The Binding property in the Properties window of VS2010 doesn't seem to know how to do what I want. Perhaps it's not possible?
One additional question: I don't think this example fits MVVM... My Counter class stands alone, is not tied to a view anywhere except through its property. However, the CounterWindow class is holding a reference to it. Is this the proper location for this reference? I also though that perhaps I should be creating the window, then setting a property (e.g. CounterObject
) that I would use instead of passing through via the constructor.
public partial class CounterWindow : Window {
Counter ctr;
public CounterWindow(Counter ctr) {
InitializeComponent();
this.ctr = ctr;
Binding b = new Binding("Count");
b.Source = ctr;
CounterLabel.SetBinding(Label.ContentProperty, b);
}
private void IncrementButton_Click(object sender, RoutedEventArgs e) {
ctr.Increment();
}
}
Upvotes: 0
Views: 276
Reputation: 37780
Something like this:
public CounterWindow(Counter ctr)
{
InitializeComponent();
DataContext = ctr;
}
Markup:
<Label Content="{Binding Count}" />
UPD.
There's two common approaches in MVVM: view-first and model-first.
View first means that you initially create the view, and then view creates view model, which it is bound to.
Model-first means that first you create the view model, then view model creates its view and passes itself (via constructor or via DataContext property setter) as data context of the view.
Hope this helps you.
Upvotes: 1