2012-04-06 94 views
0

我試圖將一個TextBox綁定到類的集合中的一個值。我該怎麼做呢?有條件的綁定?

數據:

Name, Filter 
A , 1 
B , 2 
C , 3 

現在我想,以填補我的TextBlock帶式壓濾機其中Name = A.

XAML

<TextBlock Text="{Binding [Filters.??.Filter where name =??], UpdateSourceTrigger=PropertyChanged}"></TextBlock> 

綁定到ColumnFilter

public class Model 
{ 
    private ObservableCollection<DataGridColumnFilter> _filters = new ObservableCollection<DataGridColumnFilter>(); 
    public ObservableCollection<DataGridColumnFilter> Filters { get { return _filters; } set { _filters = value; } } 
} 
public class DataGridColumnFilter 
{ 
    public string Name { get; set; } 
    public string Filter { get; set; } 
} 
+0

你有什麼期望這片神奇的結合呢?你使用什麼版本的SL? – Gabe 2012-04-06 14:34:32

+0

編輯了這個問題 – 2012-04-06 14:49:25

回答

2
名單

你應該SE轉換器:

<Page.Resources> 
    <Samples:FilterConverter x:Key="FilterConverter"/> 
</Page.Resources> 

<Grid> 
    <TextBox Text="{Binding Path=Filters, 
     Converter={StaticResource FilterConverter}, 
     ConverterParameter=a, Mode=OneWay}"/> 
</Grid> 


public class ConditionalBindingVM 
{ 
    public ConditionalBindingVM() 
    { 
     Filters = new ObservableCollection<ColumnFilter> 
         { 
          new ColumnFilter {Name = "a", Filter = "filter A"}, 
          new ColumnFilter {Name = "b", Filter = "filter B"}, 
          new ColumnFilter {Name = "c", Filter = "filter C"}, 
         }; 
    } 

    public IEnumerable<ColumnFilter> Filters { get; private set; } 
} 

public class ColumnFilter 
{ 
    public string Name { get; set; } 
    public string Filter { get; set; } 
} 

public class FilterConverter : IValueConverter 
{ 
    #region Implementation of IValueConverter 

    public object Convert(object value, Type targetType, 
          object parameter, CultureInfo culture) 
    { 
     var filters = (IEnumerable<ColumnFilter>) value; 
     var name = (string) parameter; 

     var filter = filters.SingleOrDefault(f => f.Name == name); 

     return filter != null ? filter.Filter : string.Empty; 
    } 

    public object ConvertBack(object value, Type targetType, 
      object parameter, CultureInfo culture) 
    { 
     throw new NotImplementedException(); 
    } 

    #endregion 
} 
0

使用KeyUp事件,並做到這一點(使用System.Linq的):

myTextBox.Text= Filters.FirstOrDefault(c=> c.Name.StartsWith(myTextBox.Text)).Filter;