WPF的MVVM模型的精髓之一就是数据绑定,他能做的比想象的还多。
以一个简单的按钮为实例:
这是一个录像的按钮,单机后开始录像,途中可以暂停,暂停效果如下
再次单机可以还原为播放状态。
若要在将客户端与数据源进行绑定时发出更改通知,则绑定类型应具有下列任一功能:
- 实现 INotifyPropertyChanged 接口(首选)。
- 为绑定类型的每个属性提供更改事件。
参考阅读msdn:http://msdn.microsoft.com/zh-cn/library/ms133020.aspx
xaml代码:
1 <Controls:Tile x:Name="Start_Stop_Record_Btn" Width="150" Height="72" Click="Start_Stop_Record_Btn_Click" Background="{Binding Path=Title_Color}"> 2 <Image x:Name="Start_Stop_Record_Img" Source="{Binding Path=Image_Path}" Width="64" Height="64"/> 3 </Controls:Tile>
创建title类,实现INotifyPropertyChanged接口
public partial class Title : INotifyPropertyChanged
{
private string image_path;
private string title_color;
public Title()
{
image_path = "/CamWorker;component/View/Images/light/record.png";
title_color = "#CC119EDA";
}
public string Image_Path
{
get {
return image_path;
}
set {
image_path = value;
NotifyPropertyChanged("Image_Path"); //
}
}
public string Title_Color
{
get {
return title_color;
}
set {
title_color = value;
NotifyPropertyChanged("Title_Color"); //
}
}
#region INotifyPropertyChanged Members
public event PropertyChangedEventHandler PropertyChanged;
#endregion
public void NotifyPropertyChanged(string propertyName)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
}
创建title和按钮状态标志
private Title title = new Title();
private bool pause_flag=false;//true为暂停,false为播放
在初始化设置DataContext
public MainWindow()
{
InitializeComponent();
this.Start_Stop_Record_Img.DataContext = title;
this.Start_Stop_Record_Btn.DataContext = title;
}
最后在按钮事件处理函数里面就可以调戏这些属性了。
private void Start_Stop_Record_Btn_Click(object sender, RoutedEventArgs e) { if (pause_flag) { title.Image_Path = "/CamWorker;component/View/Images/light/record.png"; title.Title_Color = "#CC119EDA"; } else { title.Image_Path = "/CamWorker;component/View/Images/light/pause.png"; title.Title_Color = "Red"; } pause_flag = !pause_flag; }
其实除了通过绑定对象来实现这种效果,还可以使用绑定转换器(converter)来实现,像这种情况在项目中还是使用后者比较好,这里不做阐述。