[英]How to bind selected Item from ListBox to ComboBox
我有一個ListBox
,項目是動態生成的。 我也有一個ComboBox
。
每個項目都有一個名為“Name”的string
屬性。
當我選擇這個項目的ListBox
,我想,設置默認值或文本ComboBox
從所選項目的“名稱” ListBox
。
我可以將其與“TextBlock”的“Text”屬性綁定。 但我不能用ComboBox
做到這一點
這是我的代碼:
XAML
<ListBox Name="MyList" ItemsSource="{Binding SourceList}"
SelectedItem="{Binding SelectedObject, Mode=TwoWay}">
<ListBox.ItemsPanel>
<ItemsPanelTemplate>
<WrapPanel Width="{Binding ElementName=MyList, Path=ActualWidth}"/>
</ItemsPanelTemplate>
</ListBox.ItemsPanel>
<ListBox.ItemTemplate>
<DataTemplate>
<Border>
<StackPanel>
<Grid>
<StackPanel>
<TextBlock {Binding Path=FileName}" />
<TextBlock>
<Run Text="{Binding Name}" />
</TextBlock>
</StackPanel>
</Grid>
</StackPanel>
</Border>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
我可以綁定這個TextBlock
:
<TextBlock>
<Run Text="{Binding SelectedItem.Name, ElementName=MyList}"/>
</TextBlock>
但它不適用於ComboBox
:
<ComboBox ItemsSource="{Binding ElementName=MyList, Path=SelectedItem}" SelectedItem="{Binding SelectedObject}" Text="{Binding Name}">
</ComboBox>
您將ComboBox
上的ItemsSource
屬性設置為ListBox
的SelectedItem
。 這不起作用,因為綁定項目源必須是一個集合,在您的情況下它是一個非集合項目。
讓我們假設您已將ItemsSource
綁定到一個集合,例如SourceList
。 然后,您可以使用DisplayMemberPath
屬性指定應用作ComboBox
標簽的屬性,此處為Name
。
<ComboBox ItemsSource="{Binding SourceList}"
SelectedItem="{Binding SelectedItem, ElementName=MyList}"
DisplayMemberPath="Name">
如果要設置默認值,可以使用Text
屬性,但也必須將IsEditable
屬性設置為true
,否則會被忽略。 從文檔:
當 IsEditable 屬性為 true 時,設置此屬性會將輸入的初始文本放置在文本框中。 當 IsEditable 為 false 時,設置此值無效。
這樣做的缺點是,會有一個默認文本,但可以編輯ComboBox
值。
<ComboBox ItemsSource="{Binding SourceList}"
SelectedItem="{Binding SelectedItem, ElementName=MyList}"
DisplayMemberPath="Name"
IsEditable="True">
如果編輯與您的要求有關,您可以查看此相關問題。 有一些解決方法,但它們非常復雜,並且也有一些缺點。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.