绑定时,项目将从集合中删除 [英] Item is removed from the collection when bound
问题描述
大家好,
我有2个对象:一个 ComboBox
和一个按钮
。我希望按钮的内容显示ComboBox的选定项目。
如果我使用字符串,一切都很好。但是当我使用其他东西时会发生一些奇怪的事情:当我改变我的选择时,组合集合被清空...... :(
我的物品是由 StackPanel
包含图像
和 TextBlock
(我替换了图像
,示例中带有 Ellipse
,但结果相同)。
这是我的代码:
Hi guys,
I have 2 objetcs: a ComboBox
and a Button
. I want the button''s content to show the ComboBox''s selected item.
Everything is fine if I work with strings. But something strange is happening when I use something else : the combo collection is emptied as I change my selection... :(
My items are made of a StackPanel
that contains an Image
and a TextBlock
(I replaced the Image
with an Ellipse
in the example but the result is the same).
Here is my code:
<Page
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:sys="clr-namespace:System;assembly=mscorlib">
<Page.Resources>
<!-- a string array -->
<x:Array x:Key="myarray1" Type="{x:Type sys:String}">
<sys:String>Item 1</sys:String>
<sys:String>Item 2</sys:String>
<sys:String>Item 3</sys:String>
<sys:String>Item 4</sys:String>
</x:Array>
<!-- an array of other type of content -->
<x:Array x:Key="myarray2" Type="{x:Type StackPanel}">
<StackPanel>
<Ellipse Width="16" Height="16" Fill="Red"/>
<TextBlock Text="Item 1"/>
</StackPanel>
<StackPanel>
<Ellipse Width="16" Height="16" Fill="Blue"/>
<TextBlock Text="Item 2"/>
</StackPanel>
<StackPanel>
<Ellipse Width="16" Height="16" Fill="Green"/>
<TextBlock Text="Item 3"/>
</StackPanel>
</x:Array>
</Page.Resources>
<!-- in the DataContext, if I change myarray2 into myarray1 everything is fine -->
<WrapPanel DataContext="{Binding Source={StaticResource myarray2}, Path=.}">
<!-- bind combo's items to the DataContext -->
<ComboBox ItemsSource="{Binding}"
IsSynchronizedWithCurrentItem="true"
Margin="5"/>
<!-- bind button's content to the combo selected item -->
<Button Content="{Binding /}"
Margin="5" />
</WrapPanel>
</Page>
现在,如果您更改组合的选择,按钮的内容会正确更新,但该项目将从组合列表中删除。
是否有人知道如何解决这个问题吗?
Now if you change the selection of the combo, the button''s content is properly updated but the item is removed from the combo''s list.
Does anyone know how to fix that?
推荐答案
如果你知道你总是绑定到TextBlock
s然后你可以设置Button
的绑定路径到
If you know that you''re always binding to the array ofTextBlock
s then you could set the binding path of theButton
to
<Button Content="{Binding Path=Text}" Margin="5"/>
/ Fredrik
/Fredrik
这篇关于绑定时,项目将从集合中删除的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!