原文:More thoughts on more thoughts on XAML, C# and WPF
Charles在他的blog上,对我提出的关于WPF数据上下文和WPF可以忽略C#代码的阐述提出了疑问。
我也会尽我所能捍卫我的阐述。
具体来讲,我很少从DependencyOjbect继承对象,并且就从我观察到的来看,离开了它,XAML和WPF在数据绑定上运行的都还不错。
XAML所依赖的只是公有的可设置的属性和不带参数的公有的构造函数。单向的数据绑定也有类似的需求。
对于双向的数据绑定,如果你执行了旧的pre-WPF接口INotifyPropertyChanged,运行起来也很棒,并且这种绑定实现起来也特别不值一提。
下面是我写的一段C#代码,我希望通过它来说明这个问题:
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;
}

接下来是一个简单的WPF/XAML窗口,我们可以用一个DataTemplate来生成和编辑它:
<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>

Trackback: http://tb.blog.csdn.net/TrackBack.aspx?PostId=1619924

浙公网安备 33010602011771号