I’ve been struggling to bind a TextBox.Text to some object’s public property but unfortunately I’m not quite there yet.
The actual XAML looks like:
<Window
<!-- skipped -->
xmlns:local="clr-namespace:Dotnet.Samples.Foobar"
xmlns:system="clr-namespace:System;assembly=mscorlib">
<Window.Resources>
<local:Foobar x:Key="foobar" Foo="Lorem" Bar="Ipsum"
</Window.Resources>
<!-- skipped -->
<TextBox Text="{Binding Source={StaticResource foobar}, Path=Foo}">
<TextBox Text="{Binding Source={StaticResource foobar}, Path=Bar}">
<!-- skipped -->
</Window>
With the data provider object being as simple as:
public class Foobar
{
public string Foo { get; set; }
public string Bar { get; set; }
public Foobar()
{
}
}
I guess I’m sort of confused with WPF’s various binding options and I’m probably mixing them up so any advice will be definitely appreciated.
EDIT — All bindings are working ok, the remaining challenge is notifying changes from the Model to the ViewModel (the other way around works). I’ve committed the ‘broken’ code to an alternative repo:
http://nanotaboada.svn.beanstalkapp.com/dotnet/trunk/Dotnet.Samples.Rijndael/
Feel free to checkout and I’d be very happy to hear about any feedback about this. Thanks much in advance
The XAML binding engine isn’t finding an appropriate constructor to use, even though your constructor method parameters are optional. Therefore, you’ll either have to pass in the values for the constructor, or create a parameterless constructor which sets the value of Foo to a default value, or don’t use the ObjectDataProvider at all, and create an instance of your type directly as a resource.
Note that you’ll only need to implement
INotifyPropertyChangedif your bindings are going to be invalidated in code, and you need to notify the UI. If you aren’t happy implementing this interface on your model types, then you can do this on your view models (assuming you’re using MVVM), but then you’ll need to find another mechanism to notify your view models when your model values change.