繁体   English   中英

WPF绑定到ListBox.Items

[英]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的数组。 请你能帮我吗?

好的,这里有些错误。

  1. 在尝试从数组中获取内容之前,您无需检查索引值。 如果没有选择会发生什么,或者如果他们选择了最后一行会发生什么?

  2. 调用列表框项目的ToString()方法将为您提供“ System.Windows.Controls.ListBoxItem:项目的文本”

  3. 最后,也许是最直接回答您的问题的事实是,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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM