[英]WPF binding to a ListBox.Items
我有一個帶有ListBox和Label的簡單窗口。 我想將Label.Text綁定到ListBox,使其成為Label中顯示的選定項之后的listBox的下一個項。 我試圖將multibinding與這樣的轉換器一起使用:
<Label>
<MultiBinding Converter="{StaticResource myConverter}">
<Binding ElementName="lbox" Path="Items"/>
<Binding ElementName="lbox" Path="SelectedIndex"/>
</MultiBinding>-->
</Label>
public class MyConverter : IMultiValueConverter
{
public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
{
object[] items = values[0] as object[];
int index = (int)(values[1]) + 1;
return (items[index]).ToString();
}
.....
}
但這行不通。 問題是我無法獲取ListBoxItems的數組。 請你能幫我嗎?
好的,這里有些錯誤。
在嘗試從數組中獲取內容之前,您無需檢查索引值。 如果沒有選擇會發生什么,或者如果他們選擇了最后一行會發生什么?
調用列表框項目的ToString()方法將為您提供“ System.Windows.Controls.ListBoxItem:項目的文本”
最后,也許是最直接回答您的問題的事實是,Items屬性不是object [],而是實際上是ItemsCollection。 您的代碼應如下所示:
public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture) { System.Windows.Controls.ItemCollection items = values[0] as System.Windows.Controls.ItemCollection; int index = (int)(values[1]) + 1; ... }
您的代碼段正確嗎? 在我看來,您需要的是SelectedIndex而不是SelectedValue(如果我正確理解了您的問題)。 那是,
<Label>
<MultiBinding Converter="{StaticResource myConverter}">
<Binding ElementName="lbox" Path="Items"/>
<Binding ElementName="lbox" Path="SelectedIndex"/>
</MultiBinding>
</Label>
請注意,至少您應該在轉換器中進行一些錯誤檢查,以檢查計算得出的索引是否仍在范圍內。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.