难倒在VB的Dependency属性中

时间:2014-10-07 23:18:25

标签: c# vb.net linq dependency-properties

我很难将Visual Basic .net转换为IValueConverter的一些C#代码,这有助于生成编号列表框。我的难点在于LINQ语句,var listBox = lbi.GetVisualAncestors ...和var index = listBox.ItemContainerGenerator ....

有人可以帮忙吗?感谢。

  using System;
  using System.Collections.Generic;
  using System.Globalization;
  using System.Linq;
  using System.Windows.Controls;
  using System.Windows.Controls.Primitives;
  using System.Windows.Data;

  namespace RowNumber
  {
     public class ListItemIndexConverter : IValueConverter
     {
        // Value should be ListBoxItem that contains the current record. RelativeSource={RelativeSource AncestorType=ListBoxItem}
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
           var lbi = (ListBoxItem)value;
           var listBox = lbi.GetVisualAncestors().OfType<ListBox>().First();
           var index = listBox.ItemContainerGenerator.IndexFromContainer(lbi);
           // One based. Remove +1 for Zero based array.
           return index + 1;
        }
        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { throw new NotImplementedException(); }
     }
     public partial class MainPage : UserControl
     {
        public MainPage()
        {
           // Required to initialize variables
           InitializeComponent();
        }
        public List<string> Test { get { return new[] { "Foo", "Bar", "Baz" }.ToList(); } }
     }
  }

1 个答案:

答案 0 :(得分:1)

所以,正如我在评论中指出的那样:)

lbi.GetVisualAncestors().OfType(Of ListBox).First()

应该做的伎俩,是的,我同意它过于冗长:D