Silverlight4Beta之Binding新特性(下)

DependencyObject支持绑定

在Silverlight4之前的版本中,只有FrameworkElement才支持数据绑定。如下场景则是不被允许的

<Canvas Width="100" Height="100" 
        RenderTransformOrigin="0.5, 0.5" Background="#FF2B6092">
    <Canvas.RenderTransform>
        <RotateTransform Angle="{Binding ElementName=slider, Path=Value}" />
    </Canvas.RenderTransform>
</Canvas>
<Slider x:Name="slider" Height="20" Margin="0,225,0,55" Minimum="0" 
        Maximum="360" />

RotateTransform当然不是FrameworkElement,而这个场景又是如此经典。sl4成全了我们

支持通过字符串索引绑定

sl4beta支持通过字符串索引绑定集合项。这意味着我们可以轻松的绑定字典对象或者提供了字符串索引的自定义类型集合。

如定义一个实体类:

public class Employee : INotifyPropertyChanged {
    private Dictionary<string, Object> _customProps;
    public Dictionary<string, Object> CustomProperties {
        get {
            if (_customProps == null)
                _customProps = new Dictionary<string, object>();
            return _customProps;
        }
    }
}

设置数据上下文

var emp = new Employee() { FirstName = "John" };
emp.CustomProperties.Add("Nickname", "Johnny");
this.DataContext = emp;

通过字符串索引绑定

<TextBox Text="{Binding Path=CustomProperties[Nickname]}"/>

ObservableCollection的新构造函数

ObservableCollection很好很强大(但是好像太长了点)将List<T>转换为ObservableCollection<T>再进行绑定是比较常见的操作。在sl4中,我们可以通过ObservableCollection的构造函数的一个重载简化这个过程。

List<string> ColorList = new List<string> { "red", "blue", "yellow" };
var ColorOC = new ObservableCollection<string>(ColorList);

另外IDataErrorInfoINotifyDataErrorInfo这两个新的验证相关的接口准备开一篇文章单独说明。

OK,have fun~

posted @ 2010-01-18 15:28  紫色永恒  阅读(1858)  评论(5编辑  收藏  举报