一个简单的示例,说明如何将后面的代码中的颜色属性绑定到画布背景。注意事项
- 实施 INotifyPropertyChanged。画布的背景将在 OnPropertyChanged 上更新,它将在每次 MyColorProperty 更改时执行。
- 设置 DataContext = this; 在构造函数中将使 Window 中的所有控件都继承此 DataContext(除非它被覆盖)。
xml
<Canvas ...>
<Canvas.Background>
<SolidColorBrush Color="{Binding MyColorProperty}"/>
</Canvas.Background>
背后的代码
public partial class MainWindow : Window, INotifyPropertyChanged
{
public MainWindow()
{
InitializeComponent();
this.DataContext = this;
}
// ...
private Color m_myColorProperty;
public Color MyColorProperty
{
get
{
return m_myColorProperty;
}
set
{
m_myColorProperty = value;
OnPropertyChanged("MyColorProperty");
}
}
public event PropertyChangedEventHandler PropertyChanged;
private void OnPropertyChanged(string propertyName)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
private void SwitchBackground()
{
if (MyColorProperty == Colors.Red)
{
MyColorProperty = Colors.Black;
}
else
{
MyColorProperty = Colors.Red;
}
}
}
更新
要运行背景动画,您可以像这样使用 BackgroundWorker
private BackgroundWorker m_changeColorBgWorker = null;
public MainWindow()
{
InitializeComponent();
this.DataContext = this;
m_changeColorBgWorker = new BackgroundWorker();
m_changeColorBgWorker.DoWork += new DoWorkEventHandler(m_changeColorBgWorker_DoWork);
}
private void button1_Click(object sender, RoutedEventArgs e)
{
if (m_changeColorBgWorker.IsBusy == false)
{
m_changeColorBgWorker.RunWorkerAsync();
}
}
void m_changeColorBgWorker_DoWork(object sender, DoWorkEventArgs e)
{
while (true)
{
for (int c = 0; c < 254; c++)
{
MyColorProperty = Color.FromArgb(255, (byte)c, (byte)(255 - c), (byte)c);
Thread.Sleep(10);
}
}
}
您可以直接在线程中设置 MyColorProperty,因为 INotifyPropertyChanged 触发的更改会自动编组回调度程序。但是,这不适用于 INotifyCollectionChanged,您知道。