Charles questions my statement about WPF data context and WPF-ignorant C# code on his blog.
I stand by my statement wholeheartedly.
Specifically, I rarely derive things from DependencyObject and as far as I've noticed, both XAML and WPF data binding works just fine without it.
XAML just relies on having public settable properties and a no-argument public constructor. One-way data binding has the same requirements.
Two way data binding works fine if you implement the old pre-WPF INotifyPropertyChanged interface, which is pretty trivial to do.
Here's a simple C# class I just wrote to illustrate this:
public class Author : INotifyPropertyChanged {
string name;
bool lovesXaml;
public bool LovesXaml {
get { return lovesXaml; }
set { lovesXaml = value; Notify("LovesXaml"); }
}
public string Name {
get { return name; }
set { name = value; Notify("Name"); }
}
// boilerplate INotifyPropertyChanged code
void Notify(string name) {
if (PropertyChanged != null)
PropertyChanged(this, new PropertyChangedEventArgs(name));
}
public event PropertyChangedEventHandler PropertyChanged;
}
And here's a trivial WPF/XAML window that uses a DataTemplate to render and edit it:
<Window x:Class='Petzold.Window1'
xmlns='http://schemas.microsoft.com/winfx/2006/xaml/presentation'
xmlns:x='http://schemas.microsoft.com/winfx/2006/xaml'
xmlns:local='clr-namespace:Petzold'
Title='Petzold'
>
<ItemsControl>
<local:Author Name='Charles Petzold' LovesXaml='true'/>
<local:Author Name='Chris Sells' LovesXaml='false'/>
<local:Author Name='Ian Griffiths' LovesXaml='true'/>
<local:Author Name='Chris Anderson' LovesXaml='false'/>
<local:Author Name='Adam Nathan' LovesXaml='true'/>
</ItemsControl>
<!-- data templates go here -->
<Window.Resources>
<DataTemplate DataType='{x:Type local:Author}'>
<StackPanel>
<StackPanel Orientation='Horizontal'>
<Label>Name:</Label>
<TextBox Text='{Binding Path=Name}'/>
</StackPanel>
<CheckBox IsChecked='{Binding LovesXaml}'>Loves XAML</CheckBox>
</StackPanel>
</DataTemplate>
</Grid.Resources>
</Grid>
</Window>
I can build the Author class in a separate DLL that has ZERO dependencies on anything other than mscorlib.dll and System.dll and it works exceedingly well.
Posted
May 10 2007, 06:46 PM
by
don-box