WPF将不同的源绑定到组合框

时间:2013-05-27 07:39:59

标签: wpf binding combobox

我有一个由文本框和组合框组成的用户控件。 我想要实现的是根据文本框中的数据将组合框项源绑定到不同的源。

例如:我有文本框输入:2米,我希望组合框填充长度单位,依此类推。所以组合框的来源将基于文本框作为长度单位,质量等。

任何人都可以帮我解决这个问题吗?

的问候。

1 个答案:

答案 0 :(得分:0)

好吧,我会用另一种方法。那些坚持MVVM的东西怎么样?

// class for all units you want to show in the UI
public class MeasureUnit : ViewModelBase // base class implementing INotifyPropertyChanged
{
    private bool _isSelectable;
    // if an item should not be shown in ComboBox IsSelectable == false
    public bool IsSelectable
    {
        get { return _isSelectable; }
        set
        {
            _isSelectable = value;
            RaisePropertyChanged(() => IsSelectable);
        }
    }

    private string _displayName;
    // the entry shown in the ComboBox
    public string DisplayName
    {
        get { return _displayName; }
        set
        {
            _displayName= value;
            RaisePropertyChanged(() => DisplayName);
        }
    }
}

现在我假设你有一个具有以下属性的VM,它将用作DataContext的{​​{1}}。

ComboBox

前端的用法可能如下所示。

private ObservableCollection<MeasureUnit> _units;
public ObservableCollection<MeasureUnit> Units
{
    get { return _units ?? (_units = new ObservableCollection<MeasureUnit>()); }
}

现在您只需要实现一些逻辑,该逻辑设置<ComboBox ItemsSource="{Binding Units}" DisplayMemberPath="DisplayName" ...> <ComboBox.Resources> <BooleanToVisibiltyConverter x:Key="Bool2VisConv" /> </ComboBox.Resources> <ComboBox.ItemTemplate> <DataTemplate> <ContentPresenter Content="{Binding}" Visibility="{Binding IsSelectable, Converter={StaticResource Bool2VisConv}}"/> </DataTemplate> </ComboBox.ItemTemplate> </ComboBox> 集合中项目的IsSelectable属性。 Units只会显示ComboBox设置为IsSelectable的项目。