Silverlight4 ColorPicker控件

原来在用一个第三方的ColorPicker控件,结果发现会导致内存泄漏。

又找了找开源的那些,没有很满意的,得,自己组装一个吧。

基本上是参考以下2篇文章组装的:

http://dotnetslackers.com/articles/silverlight/Color-Picker-Control-In-Silverlight-4.aspx

http://www.codeproject.com/KB/silverlight/Silverlight_ColorPicker.aspx

那些关键算法是在第2篇文章里的。站在巨人的肩膀上干起活来就轻便多了。

改改样式,修复下已知的Bug,调整下分块逻辑,组装。

当然还有最原始的目的,防止内存泄漏,比如:

 <Popup x:Name="Popup" IsOpen="{TemplateBinding IsOpen}"
Margin
="0,0,0,0" VerticalAlignment="Bottom">
<!--sadly,binding dp or set element in popup's child will cause memory leak-->
<!--http://blogs.telerik.com/blogs/posts/10-09-27/silverlight_4_memory_leaks_telerik_controls_and_a_solution.aspx-->
<!--<Canvas>
<StackPanel Orientation="Horizontal">
-->
<!--<local:PaletteColorPickerPart SelectedColor="{Binding SelectedColor,Mode=TwoWay,RelativeSource={RelativeSource TemplatedParent}}"/>
<local:BoardColorPickerPart SelectedColor="{Binding SelectedColor,Mode=TwoWay,RelativeSource={RelativeSource TemplatedParent}}"/>
-->
<!--<local:PaletteColorPickerPart x:Name="PaletteColorPickerPart"/>
<local:BoardColorPickerPart x:Name="BoardColorPickerPart"/>
</StackPanel>
</Canvas>
-->
</Popup>

本来可以很方便的样式里绑定下,没想到Popup会有内存泄漏问题,只能后台代码。

另外还有个用于绑定选中颜色的类:

View Code
public class PaletteColorItem : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
public event EventHandler Selected;

SolidColorBrush _brush;
bool _isSelected;

public SolidColorBrush Brush
{
get { return _brush; }
set
{
_brush
= value;
this.OnPropertyChanged("Brush");
}
}

public bool IsSelected
{
get { return _isSelected; }
set
{
_isSelected
= value;
if (_isSelected)
{
this.OnSelected();
}
this.OnPropertyChanged("IsSelected");
}
}

private void OnPropertyChanged(string propertyName)
{
var handle
= PropertyChanged;
if (handle != null)
{
handle.Invoke(
this, new PropertyChangedEventArgs(propertyName));
}
}

private void OnSelected()
{
var handle
= Selected;
if (handle != null)
{
handle.Invoke(
this, new EventArgs());
}
}
}

原来“public SolidColorBrush Brush"是直接用Color绑定的,工作良好。后来装了SL5,发现不工作了。也不知道是不是这个原因,没有仔细研究过,就先放着吧。

当然,还存在一些问题,比如选择的颜色没有变化时,下拉框不会关闭。没有最新使用的颜色这一区域。等等等。

看看效果:

还有源码:
posted @ 2011-05-16 12:04  超时空饭盒  阅读(692)  评论(2编辑  收藏  举报