我对使用ComboBox作为ItemsSource的IEnumerable<Brush>有这个问题;问题在于我(以编程方式)试图设置SelectedItem。下面是描述问题的代码:
private readonly List<Brush> colors_;
private Brush white_;
ViewModelConstructor()
{
colors_ = (from p in brushes_type.GetProperties()
select (Brush)converter.ConvertFromString(p.Name)).ToList();
white_ = colors_.Single(b => b.ToString() == "#FFFFFFFF");
}
public IEnumerable<Brush> Colors
{
get { return colors_; }
}
public Brush White
{
get { return white_; }
set
{
if (white_ != value)
white_ = value;
}
}这是xaml代码:
<ComboBox ItemsSource="{Binding Path=Colors}"
SelectedItem="{Binding Path=White}">
<ComboBox.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<Border BorderThickness="1"
BorderBrush="Black"
Width="20"
Height="12"
SnapsToDevicePixels="True"
Margin="0,0,4,0">
<Border Background="{Binding}"/>
</Border>
<TextBlock Text="{Binding}"/>
</StackPanel>
</DataTemplate>
</ComboBox.ItemTemplate>
</ComboBox>在调用get on the White属性之后,我得到一个异常:不能在对象'#FFFFFFFF‘上设置属性,因为它处于只读状态。如果我将White (white_)设为null,那么一切都正常。
发布于 2009-10-20 19:13:06
使用反光镜,我已经找到了问题出现的地方。在Selector.ItemSetIsSelected内部,它接受新的SelectedItem并执行以下操作:
如果元素的true.
DependencyObject,则如果元素E 214是DependencyObject它将D16上的E 117元素E 218设置为true.
,则将容器上的IsSelectedProperty设置为DependencyObject。
第二部分是故障发生的原因,您选择的Brush对象是只读的。由于Selector.ItemSetIsSelected在本例中有些损坏,所以有两个选项。
选项1,您只需在从转换器返回的Brush对象上调用.Clone()。
colors_ = (from p in typeof(Brushes).GetProperties()
select ((Brush)converter.ConvertFromString(p.Name)).Clone()).ToList();编辑:您应该使用选项1...Option 2来解决问题。
选项2,您可以将Brush对象包装到另一个对象中:
public class BrushWrapper
{
public Brush Brush { get; set; }
}然后更新数据模板路径:
<Border Background="{Binding Path=Brush}" />和
<TextBlock Text="{Binding Path=Brush}" />最后,更新ViewModel
private readonly List<BrushWrapper> colors_;
private BrushWrapper white_;
public ColorViewModel()
{
colors_ = (from p in typeof(Brushes).GetProperties()
select new BrushWrapper {
Brush = (Brush)converter.ConvertFromString(p.Name)
}).ToList();
white_ = colors_.Single(b => b.Brush.ToString() == "#FFFFFFFF");
}
public List<BrushWrapper> Colors
{
get { return colors_; }
}
public BrushWrapper White
{
get { return white_; }
set
{
if (white_ != value)
white_ = value;
}
}发布于 2009-10-20 15:33:19
只是在黑暗中拍摄(目前不能尝试这个),但是绑定SelectedValue而不是SelectedItem怎么样?
https://stackoverflow.com/questions/1595471
复制相似问题