2011-08-26 72 views
1

我在我的設置中有一個StringCollection,並希望將1個項目綁定到標籤。WPF綁定文本框到一個字符串集合的項目

這是如何工作的。

xmlns:p="clr-namespace:MyNamespace.Properties" 
<Label Content="{Binding Path=MyStringCollection.[2], Source={x:Static p:Settings.Default}}" /> 

但我想該指數綁定到另一個價值,並認爲這應該工作。但它沒有。

<Label Content="{Binding Path=MyStringCollection.[{Binding SelectedIndex Source={x:Static p:Settings.Default}}], Source={x:Static p:Settings.Default}}" /> 

有人能幫助我嗎?

回答

2

隨着股票WPF,你需要使用一個IMultiValueConverter:在您的XAML

public class IndexedValueConverter : IMultiValueConverter 
{ 
    public object Convert(object[] values, Type targetType, 
     object parameter, CultureInfo culture) 
    { 
     if (values.Length < 2) return null; 
     var index = Convert.ToInt32(values[1], culture); 
     var array = values[0] as Array; 
     if (array != null) return array.GetValue(index); 
     var list = values[0] as IList; 
     if (list != null) return list[index]; 
     var enumerable = values[0] as IEnumerable; 
     if (enumerable != null) 
     { 
      int ii = 0; 
      foreach (var item in enumerable) 
      { 
       if (ii++ == index) return item; 
      } 
     } 

     return null; 
    } 

// ... Implement ConvertBack as desired 

然後:

<Label> 
    <Label.Resources> 
     <local:IndexedValueConverter x:Key="Indexer" /> 
    </Label.Resources> 
    <Label.Content> 
     <MultiBinding Converter="{StaticResource Indexer}"> 
      <Binding Path="MyStringCollection" 
        Source="{x:Static p:Settings.Default}" /> 
      <Binding Path="SelectedIndex" 
        Source="{x:Static p:Settings.Default}" /> 
     </MultiBinding> 
    </Label.Content> 
</Label>