65.9K
CodeProject 正在变化。 阅读更多。
Home

构建 Silverlight 企业应用程序时的冒险 - 第 26 部分

emptyStarIconemptyStarIconemptyStarIconemptyStarIconemptyStarIcon

0/5 (0投票)

2009 年 10 月 26 日

CPOL

1分钟阅读

viewsIcon

8216

一种更通用的解决方案,用于绑定布尔值或字符串等原始类型变量

前几天,我遇到了一种需要将数据绑定到一些原始类型变量(如 boolstring)的情况。由于我不想为了解决这个问题而创建一堆类,所以我寻求一个更通用的解决方案。本文描述了该解决方案。

要求

需求很简单

  • 我应该能够将数据绑定到任何原始类型
  • 该解决方案应该易于使用
  • 该解决方案应该尽可能减少代码量

分析

经过分析,我很快意识到一个泛型类,封装实际变量会是一个不错的解决方案。我从以下代码开始

public class BindableObject<T>

一个简单的类声明,接收任何类型。显然,我需要该类支持绑定到其属性,所以我将 INotifyPropertyChanged 接口 包含在声明中,并实现了 PropertyChanged 事件和一个触发该事件的方法。

我还需要暴露一个属性来包含实际值,所以我包含了 Value 属性及其 private 字段。

现在我会写出类似这样的代码

BindableObject<bool> someObject = new BindableObject<bool>();
Binding someBinding = new Binding("Value");
someBinding.Source = someObject;
someBinding.Mode = BindingMode.TwoWay;
textBox1.SetBinding(TextBox.IsEnabledProperty, someBinding);

正如你所看到的,这仍然相当复杂。我决定添加一个方法在 BindableObject 类中进行绑定。最终我得到了一个如下所示的类

public class BindableObject<T> : INotifyPropertyChanged
{
private T _value;

public T Value 
{
get
{
return _value;
}
set
{
_value = value;
DoPropertyChanged("Value");
}
}

public void BindTo(FrameworkElement element, 
	DependencyProperty property, BindingMode mode)
{
Binding binding = newBinding("Value");
binding.Source = this;
binding.Mode = mode;
element.SetBinding(property, binding);
}

#region INotifyPropertyChanged Members

private void DoPropertyChanged(string propertyName)
{
if (PropertyChanged != null)
{
PropertyChanged.Invoke(this, newPropertyChangedEventArgs(propertyName));
}
}

public event PropertyChangedEventHandler PropertyChanged;

#endregion
}

这是一个相当简单的类。现在你可以像这样编写之前的示例

BindableObject<bool> someObject = new BindableObject<bool>();
someObject.BindTo(textBox1, TextBox.IsEnabledProperty, BindingMode.TwoWay);

我对这个方案非常满意,希望对你也有用。

© . All rights reserved.