C# 将IEnumerable作为项目来源并选择EdItem exception的组合框
我对使用IEnumerable作为ItemsSource的ComboBox有这个问题;问题在于当我以编程方式尝试设置SelectedItem时。以下是描述问题的代码:C# 将IEnumerable作为项目来源并选择EdItem exception的组合框,c#,wpf,exception,mvvm,combobox,C#,Wpf,Exception,Mvvm,Combobox,我对使用IEnumerable作为ItemsSource的ComboBox有这个问题;问题在于当我以编程方式尝试设置SelectedItem时。以下是描述问题的代码: private readonly List<Brush> colors_; private Brush white_; ViewModelConstructor() { colors_ = (from p in brushes_type.GetProperties() selec
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,则一切正常。仅在黑暗中拍摄目前无法尝试此操作,但是绑定SelectedValue而不是SelectedItem如何?使用Reflector,我已经找到了问题出现的地方。在Selector.ItemSetIsSelected内部,它接受新的SelectedItem并执行以下操作: 如果元素的容器是DependencyObject,它会将容器上的IsSelectedProperty设置为true。 否则,如果元素是DependencyObject,它会将元素的IsSelectedProperty设置为true。 第二部分是失败的原因,您选择的笔刷对象是只读的。由于Selector.ItemSetIsSelected在本例中有些不正确,因此有两个选项 选项1,您只需在转换器返回的笔刷对象上调用.Clone即可
colors_ = (from p in typeof(Brushes).GetProperties()
select ((Brush)converter.ConvertFromString(p.Name)).Clone()).ToList();
编辑:您应该选择选项1…选项2是解决问题的冗长方法
选项2,可以将笔刷对象包装为一个或多个对象:
public class BrushWrapper
{
public Brush Brush { get; set; }
}
然后更新数据模板路径:
<Border Background="{Binding Path=Brush}" />
我们能看到异常的调用堆栈吗?我已经在上传了调用堆栈。只需将DOC重命名为TXT wordpress limition.Odd。。正如六个变量所问:异常的调用堆栈可能会有所帮助。是的,这很奇怪。。。我已经建立了调用堆栈,但是除了一行之外的每一行都来自框架。不仅仅是combobox,还有listbox,我想任何ItemsControl都是一样的。没问题。我强烈建议使用Reflector,因为它帮助解决了很多WPF的古怪问题。WPF有时会有悖常理
<TextBlock Text="{Binding Path=Brush}" />
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;
}
}