基于Cairngorm的Silverlight开发 - part4
通过绑定用视图来管理ModelLocator
由于绑定是双向的,所以在绑定到一些可以操作其自身属性的的控件时,对ModelLocator也是有影响的。这里把上边事例中的颜色的RGB值分别绑定到三个Slider控件上。
public ColorConfig()
{
InitializeComponent();
this.Loaded += new RoutedEventHandler(ColorConfig_Loaded);
}
void ColorConfig_Loaded(object sender, RoutedEventArgs e)
{
ByteConverter bc=new ByteConverter();
this.DataContext = BackGroundModel.Instance;
Binding bindR = new Binding("R");
bindR.Mode = BindingMode.TwoWay;
bindR.Converter = bc;
xRSlider.SetBinding(Slider.ValueProperty, bindR);
Binding bindG = new Binding("G");
bindG.Mode = BindingMode.TwoWay;
bindG.Converter = bc;
xGSlider.SetBinding(Slider.ValueProperty, bindG);
Binding bindB = new Binding("B");
bindB.Mode = BindingMode.TwoWay;
bindB.Converter = bc;
xBSlider.SetBinding(Slider.ValueProperty, bindB);
}
这里用到了一个数据值的转换,有时需要把一个图片绑定到控件上,但是只有图片的Uri是不行的,要做一步转换。我给出的代码片段都是最简单的。public class ByteConverter:IValueConverter
{
public object Convert(
object value,
Type targetType,
object parameter,
CultureInfo culture)
{
int b = System.Convert.ToInt32(value);
return (byte)b;
}
public object ConvertBack(
object value,
Type targetType,
object parameter,
CultureInfo culture)
{
byte b = System.Convert.ToByte(value);
return (int)b;
}
}
送上视频 :)
ViewManagerP2.wmv