有条件的绑定?

时间:2012-04-06 14:06:30

标签: silverlight xaml silverlight-4.0

我正在尝试将TextBox绑定到类Collection的值。我该怎么做?

数据:

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

现在我想用Filter填充我的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; }
}

2 个答案:

答案 0 :(得分:2)

你应该使用转换器:

<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
}

答案 1 :(得分:0)

使用KeyUp事件并执行此操作(使用System.Linq):

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